本文整理汇总了Golang中net.TCPConn.SetReadBuffer方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPConn.SetReadBuffer方法的具体用法?Golang TCPConn.SetReadBuffer怎么用?Golang TCPConn.SetReadBuffer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPConn
的用法示例。
在下文中一共展示了TCPConn.SetReadBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handlerConnection
//处理连接请求
func (this *server) handlerConnection(conn *net.TCPConn) {
defer logger.CatchException()
logger.Infof("New connection coming ... IP=%s ", conn.RemoteAddr())
conn.SetNoDelay(true) //无延迟
conn.SetKeepAlive(true) //保持激活
conn.SetReadBuffer(64 * 1024) //设置读缓冲区大小
conn.SetWriteBuffer(64 * 1024) //设置写缓冲区大小
conn.SetReadDeadline(time.Now().Add(30000000 * time.Second)) //设置读超时
session := network.NewSession(conn)
defer session.Close()
for {
msg, err := session.RecvMSG()
if err != nil {
logger.Infof("RecvMsgs IP=%s err=%v", conn.RemoteAddr(), err.Error())
return
}
ret := this.ProcessMessage(session, msg)
if ret == false {
return
}
}
}
示例2: Start
func (server *TcpServer) Start() (err error) {
for {
var conn *net.TCPConn
if conn, err = server.TCPListener.AcceptTCP(); err != nil {
return err
}
if server.keepAlive != nil {
if err := conn.SetKeepAlive(server.keepAlive.(bool)); err != nil {
return err
}
}
if server.keepAlivePeriod != nil {
if kap, ok := (net.Conn(conn)).(iKeepAlivePeriod); ok {
if err := kap.SetKeepAlivePeriod(server.keepAlivePeriod.(time.Duration)); err != nil {
return err
}
}
}
if server.linger != nil {
if err := conn.SetLinger(server.linger.(int)); err != nil {
return err
}
}
if server.noDelay != nil {
if err := conn.SetNoDelay(server.noDelay.(bool)); err != nil {
return err
}
}
if server.readBuffer != nil {
if err := conn.SetReadBuffer(server.readBuffer.(int)); err != nil {
return err
}
}
if server.writerBuffer != nil {
if err := conn.SetWriteBuffer(server.writerBuffer.(int)); err != nil {
return err
}
}
if server.deadline != nil {
if err := conn.SetDeadline(server.deadline.(time.Time)); err != nil {
return err
}
}
if server.readDeadline != nil {
if err := conn.SetReadDeadline(server.readDeadline.(time.Time)); err != nil {
return err
}
}
if server.writerDeadline != nil {
if err := conn.SetWriteDeadline(server.writerDeadline.(time.Time)); err != nil {
return err
}
}
if server.config != nil {
server.ServeTCP(tls.Client(conn, server.config))
} else {
server.ServeTCP(conn)
}
}
}
示例3: newConn
// NewConn creates a new connection for the sio. It generates the session id and
// prepares the internal structure for usage.
func newConn(serv *Server, fd uint32, nc *net.TCPConn) (c *Conn, err error) {
host, _, err := net.SplitHostPort(nc.RemoteAddr().String())
if err != nil {
serv.Log("mudoo/newConn: GetRemoteAddr:", err)
return
}
c = &Conn{
serv: serv,
fd: fd,
nc: nc,
raddr: host,
online: true,
lastConnected: time.Now().UnixNano(),
wakeupFlusher: make(chan byte),
wakeupReader: make(chan byte),
numConns: 0,
numHeartbeats: 0,
decBuf: new(Buffer),
}
nc.SetReadBuffer(serv.config.ReadBufferSize)
nc.SetWriteBuffer(serv.config.WriteBufferSize)
go c.keepalive()
// go c.flusher()
go c.reader()
return
}
示例4: read_tcp_conn
func read_tcp_conn(tcpConn *net.TCPConn, connChan chan []byte) {
buffer := make([]byte, 2048)
tcpConn.SetReadBuffer(2048)
for {
n, err := tcpConn.Read(buffer[0:])
if err != nil {
log.Println("one tcp connection read function failed!")
log.Println("one tcp connection close now!")
tcpConn.Close()
runtime.Goexit()
} else {
connChan <- buffer[0 : n-1]
}
}
}
示例5: AcceptTCP
// Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks; the caller typically
// invokes it in a go statement.
func (server *Server) AcceptTCP(lis *net.TCPListener, i int) {
var (
conn *net.TCPConn
err error
)
for {
log.Debug("server: accept round: %d", i)
if conn, err = lis.AcceptTCP(); err != nil {
// if listener close then return
log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
return
}
if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
log.Error("conn.SetKeepAlive() error(%v)", err)
return
}
if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
log.Error("conn.SetReadBuffer() error(%v)", err)
return
}
if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
log.Error("conn.SetWriteBuffer() error(%v)", err)
return
}
go server.serveConn(conn, i)
if i++; i == maxInt {
i = 0
}
}
}
示例6: connectPeer
func (peers *Peers) connectPeer(hostName string, portNumber int, conn *net.TCPConn) {
peer, err := peers.getPeer(hostName, portNumber)
checkError(err)
err = conn.SetReadBuffer(ChunkSize)
checkError(err)
readBuffer := make([]byte, ChunkSize)
_, err = conn.Read(readBuffer)
checkError(err)
var fileList FileList
readBuffer = bytes.TrimRight(readBuffer, "\x00")
err = json.Unmarshal(readBuffer, &fileList)
checkError(err)
if peer.currentState != Connected {
updateStatus(hostName, portNumber, fileList.Files)
peers.numPeers += 1
}
peer.currentState = Connected
return
}
示例7: downloadFile
func (peer Peer) downloadFile(file File, conn *net.TCPConn) {
if f, ok := status.status["local"].files[file.FileName]; ok {
if f.Chunks[file.Chunks[1]] == 1 {
return
}
} else {
chunks := make([]int, file.Chunks[0])
for chunk := range chunks {
chunks[chunk] = 0
}
chunks[file.Chunks[1]] = 1
status.status["local"].files[file.FileName] = File{
FileName: file.FileName,
Chunks: chunks,
}
}
status.status["local"].files[file.FileName].Chunks[file.Chunks[1]] = 1
incrementChunkReplication(file.FileName, file.Chunks[1], file.Chunks[0])
err := conn.SetReadBuffer(ChunkSize)
checkError(err)
readBuffer := make([]byte, ChunkSize)
_, err = conn.Read(readBuffer)
checkError(err)
conn.Close()
status.mu.Lock()
basepath := path.Dir(file.FileName)
fileName := path.Base(file.FileName)
err = os.MkdirAll(basepath, 0777)
checkError(err)
filePath := path.Join(basepath, fileName)
localFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0777)
if err != nil {
for {
localFile, err = os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0777)
if err == nil {
break
}
}
}
writeOffset := int64(file.Chunks[1] * ChunkSize)
_, err = localFile.WriteAt(bytes.TrimRight(readBuffer, "\x00"), writeOffset)
checkError(err)
err = localFile.Close()
checkError(err)
status.mu.Unlock()
fmt.Printf("Downloaded file %s:%d \n\n", file.FileName, file.Chunks[1])
fileList := []File{file}
haveMessage := encodeMessage(peer.host, peer.port, Have, fileList)
sendToAll(haveMessage)
return
}
示例8: acceptTCP
// Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks; the caller typically
// invokes it in a go statement.
func acceptTCP(server *Server, lis *net.TCPListener) {
var (
conn *net.TCPConn
err error
r int
)
for {
if conn, err = lis.AcceptTCP(); err != nil {
// if listener close then return
log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
return
}
if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
log.Error("conn.SetKeepAlive() error(%v)", err)
return
}
if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
log.Error("conn.SetReadBuffer() error(%v)", err)
return
}
if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
log.Error("conn.SetWriteBuffer() error(%v)", err)
return
}
go serveTCP(server, conn, r)
if r++; r == maxInt {
r = 0
}
}
}
示例9:
func configureConn (conn *net.TCPConn, spec *ConnectionSpec) {
// these two -- the most important -- are causing problems on my osx/64
// where a "service unavailable" pops up in the async reads
// but we absolutely need to be able to use timeouts.
// conn.SetReadTimeout(spec.rTimeout);
// conn.SetWriteTimeout(spec.wTimeout);
conn.SetLinger(spec.lingerspec);
conn.SetKeepAlive(spec.keepalive);
conn.SetReadBuffer(spec.rBufSize);
conn.SetWriteBuffer(spec.wBufSize);
}
示例10: handle_logic
// 每个连接在此函数中完成所有事情,不再启动多个协程
func handle_logic(clientConn *net.TCPConn) {
defer func() { // 必须要先声明defer,否则不能捕获到panic异常
if err := recover(); err != nil {
jlog.Critical("!!!!!!!!!!!!! LOGIC FANIC error: ", err)
//fmt.Println("!!!!!!!!!!!!! LOGIC FANIC error: ", err)
clientConn.Close()
runtime.Goexit()
}
}()
tcpBuffer := make([]byte, nfconst.LEN_TCP_BUFFER)
clientConn.SetReadBuffer(nfconst.LEN_TCP_BUFFER)
var handle *nfnet.OrgStreamHandler = nfnet.NewOrgStreamHandler()
nullmsg := make([]byte, 0)
var msg []byte
for {
n, err := clientConn.Read(tcpBuffer[0:])
if err != nil {
if err.Error() == "EOF" {
// 跳出循环, 并处理已经接收到的数据
jlog.Infof("%s close, tcp read end, break read loop", clientConn.RemoteAddr().String())
} else {
jlog.Errorf("%s tcp read error %s, break read loop", clientConn.RemoteAddr().String(), err.Error())
}
//jlog.Tracef("---------- D_%s, read err: %s", clientConn.RemoteAddr().String(), err.Error())
clientConn.Close()
jlog.Infof("==================== goroutine exit\n")
runtime.Goexit()
break
}
done, buf, err1 := handle.AddStream(tcpBuffer[0:n])
msg = buf
if err1 != nil {
jlog.Error("data add stream error, ", err1.Error())
} else if done {
// 处理消息
msgHandler(clientConn, msg)
msg = nullmsg
}
}
// 如果执行到了这里, 那么就是 read的时候发生错误到了此处
// 一个完整的包具备的最小长度为 头2字节,cmd 1字节, 负载长度2字节,校验1字节,尾2字节 = 8字节
/*
n_msg := len(msg)
if n_msg >= nfconst.LEN_MIN_PACKAGE && msg[0] == nfconst.SOCK_PACK_HEADER_L && msg[1] == nfconst.SOCK_PACK_HEADER_H &&
msg[n_msg-2] == nfconst.SOCK_PACK_ENDER_L && msg[n_msg-1] == nfconst.SOCK_PACK_ENDER_H {
msgHandler(clientConn, msg)
}
*/
}
示例11: setupSocket
func (server *Server) setupSocket(conn *net.TCPConn) (err error) {
if err = conn.SetLinger(0); err != nil {
return
}
if server.ConfigReadBuffer != 0 {
if err = conn.SetReadBuffer(int(server.ConfigReadBuffer)); err != nil {
return
}
}
if err = conn.SetKeepAlive(true); err != nil {
return
}
if err = conn.SetReadDeadline(time.Now().Add(server.ConfigIdleTimeout)); err != nil {
return
}
return
}
示例12: TCPConnRead
func TCPConnRead(c *net.TCPConn) error {
c.SetReadBuffer(*packetsize)
for {
_, err := c.Read(b)
if err != nil {
if err == io.EOF {
log.Println("Client ", c.RemoteAddr(), " disconnected")
c.Close()
return nil
} else {
log.Println("Failed reading bytes from conn: ", c, " with error ", err)
c.Close()
return err
}
}
}
return nil
}
示例13: pipe
func (p *proxy) pipe(src, dst *net.TCPConn) {
//data direction
var f, h string
islocal := src == p.lconn
if *verbose {
if islocal {
f = ">>> %d bytes sent%s"
} else {
f = "<<< %d bytes recieved%s"
}
}
h = "%s"
//directional copy
buff := make([]byte, 0xffff)
src.SetReadBuffer(len(buff))
for {
n, err := src.Read(buff)
if err != nil {
p.err("Read failed '%s'\n", err)
return
}
b := buff[:n]
//show output
if *veryverbose {
p.log(fmt.Sprintf(f, n, "\n"+fmt.Sprintf(h, b)))
} else if *verbose {
p.log(fmt.Sprintf(f, n, ""))
}
//write out result
n, err = dst.Write(b)
if err != nil {
p.err("Write failed '%s'\n", err)
return
}
if islocal {
p.sentBytes += uint64(n)
} else {
p.receivedBytes += uint64(n)
}
}
}
示例14: handleConnection
func handleConnection(conn *net.TCPConn) {
defer conn.Close()
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
return
}
}()
conn.SetKeepAlive(true)
conn.SetReadBuffer(4096)
conn.SetWriteBuffer(4096)
handler := NewHandler(conn)
accu := lendecoder.NewAccumulator(handler, 2, 1200)
err := accu.ReadFrom(conn)
if err != nil {
fmt.Printf("Error: %v\n", err)
}
}
示例15: NewSession
func NewSession(conn *net.TCPConn, rc *turbo.RemotingConfig) *Session {
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(rc.IdleTime * 2)
//禁用nagle
conn.SetNoDelay(true)
conn.SetReadBuffer(rc.ReadBufferSize)
conn.SetWriteBuffer(rc.WriteBufferSize)
session := &Session{
conn: conn,
br: bufio.NewReaderSize(conn, rc.ReadBufferSize),
bw: bufio.NewWriterSize(conn, rc.WriteBufferSize),
ReadChannel: make(chan *packet.Packet, rc.ReadChannelSize),
WriteChannel: make(chan *packet.Packet, rc.WriteChannelSize),
isClose: false,
remoteAddr: conn.RemoteAddr().String(),
rc: rc}
return session
}