本文整理汇总了Golang中bufio.NewReadWriter函数的典型用法代码### 示例。如果您正苦于以下问题:Golang NewReadWriter函数的具体用法?Golang NewReadWriter怎么用?Golang NewReadWriter使用的例子?那么恭喜您, 这里精选的函数代码### 示例或许可以为您提供帮助。
在下文中一共展示了NewReadWriter函数的20个代码### 示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码### 示例。
示例1: main
func main() {
addr, _ := net.ResolveTCPAddr("0.0.0.0:9009")
go func() {
l, _ := net.ListenTCP("tcp", addr)
conn, _ := l.AcceptTCP()
println("accepted")
go func(c io.ReadWriter) {
buf := make([]byte, N)
b := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
if n, e := b.Read(buf); e != nil || n < N {
println("read", n, e.String())
return
}
if n, e := b.Write(buf); n < N || e != nil {
println("write", n, e.String())
}
b.Flush()
time.Sleep(1)
}(conn)
}()
time.Sleep(1e9)
c, _ := net.DialTCP("tcp", nil, addr)
println("connected")
f := bufio.NewReadWriter(bufio.NewReader(c), bufio.NewWriter(c))
b := make([]byte, N)
if n, e := f.Write(b); n < N || e != nil {
panic("write failed")
}
f.Flush()
if n, e := f.Read(b); e != nil || n < N {
println("read 2", n, e.String())
}
}
开发者ID:haiger,项目名称:beansdb,代码行数:33,代码来源:main.go
示例2: main
func main() {
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*baidu.com$"))).
HandleConnect(goproxy.AlwaysReject)
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
HandleConnect(goproxy.AlwaysMitm)
// enable curl -p for all hosts on port 80
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
defer func() {
if e := recover(); e != nil {
ctx.Logf("error connecting to remote: %v", e)
client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
}
client.Close()
}()
clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
remote, err := net.Dial("tcp", req.URL.Host)
orPanic(err)
remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
for {
req, err := http.ReadRequest(clientBuf.Reader)
orPanic(err)
orPanic(req.Write(remoteBuf))
orPanic(remoteBuf.Flush())
resp, err := http.ReadResponse(remoteBuf.Reader, req)
orPanic(err)
orPanic(resp.Write(clientBuf.Writer))
orPanic(clientBuf.Flush())
}
})
proxy.Verbose = true
log.Fatal(http.ListenAndServe(":8080", proxy))
}
开发者ID:LivingInPortal,项目名称:goproxy,代码行数:34,代码来源:main.go
示例3: wshandler
func wshandler(ws *websocket.Conn) {
flag.Parse()
var mqcon net.Conn
var err error
if *bs {
conf := tls.Config{InsecureSkipVerify: *bsinsec}
if *bcert != "" && *bkey != "" {
Cert, err := tls.LoadX509KeyPair(*bcert, *bkey)
if err != nil {
fmt.Println("LoadX509KeyPair:", err)
return
}
conf.Certificates = []tls.Certificate{Cert}
}
mqcon, err = tls.Dial("tcp", *bhost+":"+*bport, &conf)
} else {
mqcon, err = net.Dial("tcp", *bhost+":"+*bport)
}
if err != nil {
fmt.Println("mqcon error:", err.Error())
ws.Close()
return
}
ws.PayloadType = websocket.BinaryFrame
bmqcon := bufio.NewReadWriter(bufio.NewReader(mqcon), bufio.NewWriter(mqcon))
bws := bufio.NewReadWriter(bufio.NewReader(ws), bufio.NewWriter(ws))
go func() {
for {
msg, err := mqtt.DecodeOneMessage(bmqcon, nil)
// fmt.Println("brok->", msg)
if err != nil {
mqcon.Close()
return
}
wbuffer := new(bytes.Buffer)
msg.Encode(wbuffer)
bws.Write(wbuffer.Bytes())
bws.Flush()
wbuffer.Truncate(wbuffer.Len())
}
}()
for {
msg, err := mqtt.DecodeOneMessage(bws, nil)
// fmt.Println("webs->", msg)
if err != nil {
ws.Close()
return
}
msg.Encode(bmqcon)
bmqcon.Flush()
}
}
开发者ID:taoyonggang,项目名称:mqttwss,代码行数:55,代码来源:mqttwss.go
示例4: newConn
func (s *Server) newConn(rwc net.Conn) (c *conn, err error) {
c = new(conn)
c.server = s
c.conn = rwc
c.rwc = bufio.NewReadWriter(bufio.NewReaderSize(rwc, 1048576), bufio.NewWriter(rwc))
return c, nil
}
开发者ID:ningjh,项目名称:go-memcached,代码行数:7,代码来源:server.go
示例5: newConn
func newConn(rwc net.Conn) *conn {
return &conn{
rwc: rwc,
buf: bufio.NewReadWriter(bufio.NewReader(rwc), bufio.NewWriter(rwc)),
done: make(chan bool, 1),
}
}
开发者ID:rboyer,项目名称:rpc,代码行数:7,代码来源:server.go
示例6: NewClient
// NewClient creates a new WebSocket client connection over rwc.
func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) {
br := bufio.NewReader(rwc)
bw := bufio.NewWriter(rwc)
switch config.Version {
case ProtocolVersionHixie75:
err = hixie75ClientHandshake(config, br, bw)
case ProtocolVersionHixie76, ProtocolVersionHybi00:
err = hixie76ClientHandshake(config, br, bw)
case ProtocolVersionHybi08, ProtocolVersionHybi13:
err = hybiClientHandshake(config, br, bw)
default:
err = ErrBadProtocolVersion
}
if err != nil {
return
}
buf := bufio.NewReadWriter(br, bw)
switch config.Version {
case ProtocolVersionHixie75, ProtocolVersionHixie76, ProtocolVersionHybi00:
ws = newHixieClientConn(config, buf, rwc)
case ProtocolVersionHybi08, ProtocolVersionHybi13:
ws = newHybiClientConn(config, buf, rwc)
}
return
}
开发者ID:aubonbeurre,项目名称:gcc,代码行数:26,代码来源:client.go
示例7: pubWorker
func pubWorker(n int, tcpAddr string, batchSize int, batch [][]byte, topic string) {
conn, err := net.DialTimeout("tcp", tcpAddr, time.Second)
if err != nil {
panic(err.Error())
}
conn.Write(nsq.MagicV2)
rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
num := n / runtime.GOMAXPROCS(0) / batchSize
for i := 0; i < num; i += 1 {
cmd, _ := nsq.MultiPublish(topic, batch)
err := cmd.Write(rw)
if err != nil {
panic(err.Error())
}
err = rw.Flush()
if err != nil {
panic(err.Error())
}
resp, err := nsq.ReadResponse(rw)
if err != nil {
panic(err.Error())
}
_, data, _ := nsq.UnpackResponse(resp)
if !bytes.Equal(data, []byte("OK")) {
panic("invalid response")
}
}
}
开发者ID:sunminghong,项目名称:nsq,代码行数:29,代码来源:bench_writer.go
示例8: handleRequest
// protoRead reads binary blobs with the following format:
//
// COMMAND ' ' CHANNEL ' ' SIZE PAYLOAD
func (s *Server) handleRequest(conn net.Conn) {
r := bufio.NewReader(conn)
rw := bufio.NewReadWriter(r, nil)
var payloadSize int64
err := binary.Read(rw, binary.BigEndian, &payloadSize)
var buf bytes.Buffer
io.CopyN(&buf, rw, payloadSize)
body := buf.Bytes()
blobs := bytes.SplitN(body, []byte(" "), 2)
command := string(blobs[0])
channel := string(blobs[1])
payload := blobs[2]
reply, err := s.processCommand(command, channel, payload)
if err != nil {
fmt.Println("Error processing command:", err)
return
}
conn.Write([]byte(reply))
// Close the connection when you're done with it.
conn.Close()
}
开发者ID:toqueteos,项目名称:pubsub,代码行数:30,代码来源:server.go
示例9: newConn
func newConn(rwc io.ReadWriteCloser) *Conn {
return &Conn{
stream: bufio.NewReadWriter(
bufio.NewReader(rwc),
bufio.NewWriter(rwc)),
}
}
开发者ID:sebnow,项目名称:ircgo,代码行数:7,代码来源:irc.go
示例10: readData
func readData(client net.Conn) {
b := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
i := 0
var err error
var tx *sql.Tx
for {
if i == 0 {
tx, err = pg.Begin()
if err != nil {
log.Printf("error=true action=begin message=%v", err)
}
i += 1
} else if i == (*checkpoint + 1) {
//checkpoint is set by flag
// we inc checkpoint for the case when it is set to 1
err = tx.Commit()
if err != nil {
log.Printf("error=true action=commit message=%v", err)
}
log.Printf("action=commit")
i = 0
} else {
line, err := b.ReadString('\n')
if err != nil {
break
}
handleInput(*tx, line)
i += 1
}
}
}
开发者ID:ryandotsmith,项目名称:wcld,代码行数:31,代码来源:wcld.go
示例11: TestAuthFailed
func TestAuthFailed(t *testing.T) {
server := strings.Join(strings.Split(authFailedServer, "\n"), "\r\n")
client := strings.Join(strings.Split(authFailedClient, "\n"), "\r\n")
var cmdbuf bytes.Buffer
bcmdbuf := bufio.NewWriter(&cmdbuf)
var fake faker
fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)
c, err := NewClient(fake, "fake.host")
if err != nil {
t.Fatalf("NewClient: %v", err)
}
defer c.Close()
c.tls = true
c.serverName = "smtp.google.com"
err = c.Auth(PlainAuth("", "user", "pass", "smtp.google.com"))
if err == nil {
t.Error("Auth: expected error; got none")
} else if err.Error() != "535 Invalid credentials\nplease see www.example.com" {
t.Errorf("Auth: got error: %v, want: %s", err, "535 Invalid credentials\nplease see www.example.com")
}
bcmdbuf.Flush()
actualcmds := cmdbuf.String()
if client != actualcmds {
t.Errorf("Got:\n%s\nExpected:\n%s", actualcmds, client)
}
}
开发者ID:achanda,项目名称:go,代码行数:29,代码来源:smtp_test.go
示例12: SendTestMessage
// Send the given email messages using this Mailer.
func (m *Mailer) SendTestMessage(basicServer string, messages ...*Message) (actualcmds string, err error) {
if m.Auth == nil {
m.Auth = smtp.PlainAuth(m.UserName, m.UserName, m.Password, m.Server)
}
server := strings.Join(strings.Split(basicServer, "\n"), "\r\n")
var cmdbuf bytes.Buffer
bcmdbuf := bufio.NewWriter(&cmdbuf)
var fake faker
fake.ReadWriter = bufio.NewReadWriter(bufio.NewReader(strings.NewReader(server)), bcmdbuf)
defer func() {
bcmdbuf.Flush()
actualcmds = cmdbuf.String()
}()
c, err := smtp.NewClient(fake, "fake.host")
if err != nil {
return
}
defer c.Quit()
for _, message := range messages {
m.fillDefault(message)
if err = Send(c, message); err != nil {
return
}
}
return
}
开发者ID:nangong92t,项目名称:go_src,代码行数:32,代码来源:mailer_test.go
示例13: newConn
func (s *Server) newConn(originalConn net.Conn) *conn {
c := new(conn)
c.server = s
c.conn = originalConn
c.rw = bufio.NewReadWriter(bufio.NewReader(originalConn), bufio.NewWriter(originalConn))
return c
}
开发者ID:json007,项目名称:goleveldb,代码行数:7,代码来源:server.go
### 示例14: identd
点赞 1
func identd(port string) {
identd, err := net.Listen("tcp", "0.0.0.0:"+port)
if err != nil {
fmt.Println("Failed to start identd on port", port)
return
}
defer identd.Close()
fmt.Println("Started identd on port", port)
for {
conn, err := identd.Accept()
if err != nil {
fmt.Println("Failed to accept identd connection")
continue
}
io := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
line, err := io.Reader.ReadString('\n')
if err != nil || len(line) < 2 {
conn.Close()
fmt.Println("Failed to read identd request")
continue
}
line = line[:len(line)-2]
line = fmt.Sprintf("%s : ERROR : NO-USER\r\n", line)
io.Writer.WriteString(line)
time.Sleep(1000000000) // 1 second
conn.Close()
}
}
开发者ID:raylu,项目名称:rbot,代码行数:30,代码来源:rbot.go
示例15: NewAOF
// NewAOF ...
func NewAOF(path string) *AOF {
file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0600)
utils.PanicOnError(err)
rdr := bufio.NewReader(file)
wtr := bufio.NewWriter(file)
return &AOF{file, bufio.NewReadWriter(rdr, wtr), sync.RWMutex{}}
}
开发者ID:silky,项目名称:skizze,代码行数:8,代码来源:aof.go
示例16: Hijack
// Hijack takes a net.Conn and the host name to create the SSL
// certificate for and returns a tls.Conn that can read and write
// to the given host over TLS.
func (mitm *MITM) Hijack(conn net.Conn, host string) (*tls.Conn, *bufio.ReadWriter, error) {
// Ensure the certificate we create is valid within a window of time to allow
// for clock skew.
start := time.Now().Add(-mitm.Validity)
end := time.Now().Add(mitm.Validity)
tpl, err := NewTemplate(mitm.Organization, host, start, end, mitm.PublicKey)
if err != nil {
return nil, nil, err
}
cb, err := x509.CreateCertificate(rand.Reader, tpl, mitm.Authority, mitm.PublicKey, mitm.PrivateKey)
if err != nil {
return nil, nil, err
}
config := &tls.Config{
Certificates: []tls.Certificate{
{
PrivateKey: mitm.PrivateKey,
Certificate: [][]byte{cb},
},
},
}
tlsConn := tls.Server(conn, config)
r := bufio.NewReader(tlsConn)
w := bufio.NewWriter(tlsConn)
return tlsConn, bufio.NewReadWriter(r, w), nil
}
开发者ID:eolexe,项目名称:martian,代码行数:34,代码来源:mitm.go
示例17: Hijack
func (rw *hijackResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
rw.hijacked = true
br := bufio.NewReader(rw.conn)
bw := bufio.NewWriter(rw.conn)
return rw.conn, bufio.NewReadWriter(br, bw), nil
}
开发者ID:hanscj1,项目名称:martian,代码行数:7,代码来源:proxy_test.go
示例18: TestBulkBytes
func TestBulkBytes(t *testing.T) {
b := &bytes.Buffer{}
c := &redisConnection{
nc: nil,
rw: bufio.NewReadWriter(bufio.NewReader(b), bufio.NewWriter(b)),
buf: make([]byte, 24),
}
by := []byte{1, 2, 3, 4}
if err := c.writeBulkBytes(by); err != nil {
t.Fatalf("Error during writeBulkBytes: %s", err)
}
if err := c.writeBulkBytes(by); err != nil {
t.Fatalf("Error during writeBulkBytes: %s", err)
}
c.rw.Flush()
if o, err := c.readBulkBytes(); err != nil {
t.Fatalf("Error during readBulkBytes: %s", err)
} else if !bytes.Equal(o, by) {
t.Fatalf("write/readBulkBytes returned wrong balue %+v expected %+v", o, by)
}
if o, err := c.readBulkBytes(); err != nil {
t.Fatalf("Error during readBulkBytes: %s", err)
} else if !bytes.Equal(o, by) {
t.Fatalf("write/readBulkBytes returned wrong balue %+v expected %+v", o, by)
}
}
开发者ID:samuel,项目名称:go-redis,代码行数:26,代码来源:connection_test.go
示例19: TestReadDataPacketOK
func TestReadDataPacketOK(t *testing.T) {
byteBuf := []byte("DATA 1 46\r\n{\"action\":\"foo\",\"version\":1,\"envelope\":\"json\"}END\r\n")
byteReader := bufio.NewReader(bytes.NewReader(byteBuf))
byteRdrWrtr := bufio.NewReadWriter(byteReader, nil)
packet, err := ReadPacket(byteRdrWrtr)
if err != nil {
t.Errorf("got err `%s`", err)
t.FailNow()
}
if packet.packetType != DATA {
t.Errorf("packetType was not parsed correctly. packet.packetType: `%d`", packet.packetType)
t.FailNow()
}
expectedBody := []byte(`{"action":"foo","version":1,"envelope":"json"}`)
if !bytes.Equal(packet.body, expectedBody) {
t.Errorf("bad packet body parse. expected `%s`, got: `%s`", expectedBody, packet.body)
t.FailNow()
}
emptyHeader := PacketHeader{}
if packet.packetHeader != emptyHeader {
t.Errorf("packet header should not be set")
t.FailNow()
}
}
开发者ID:gudTECH,项目名称:scamp-go,代码行数:26,代码来源:packet_test.go
示例20: newClient
func newClient(socket net.Conn, version, maxBatch int) (client *Client, err error) {
readWriter := bufio.NewReadWriter(bufio.NewReader(socket), bufio.NewWriter(socket))
heloRequest := &HeloRequest{
Version: version,
MaxBatch: maxBatch,
}
if _, err = heloRequest.WriteTo(readWriter); err != nil {
return nil, err
}
if err = readWriter.Flush(); err != nil {
return nil, err
}
heloReply := &HeloReply{}
if _, err = heloReply.ReadFrom(readWriter); err != nil {
return nil, err
}
if heloReply.Version != version {
if err = socket.Close(); err != nil {
return nil, err
}
return nil, ErrUnsupportedVersion
}
client = &Client{
Version: version,
socket: socket,
readWriter: readWriter,
}
return
}
开发者ID:kitcambridge,项目名称:csor,代码行数:33,代码来源:client.go