本文整理汇总了Golang中net.TCPConn.SetDeadline方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPConn.SetDeadline方法的具体用法?Golang TCPConn.SetDeadline怎么用?Golang TCPConn.SetDeadline使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPConn
的用法示例。
在下文中一共展示了TCPConn.SetDeadline方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleConnection
func handleConnection(conn *net.TCPConn) error {
defer conn.Close()
handlerChan <- 1
defer func() {
handlerChan <- -1
}()
var ws *websocket.Conn
conn.SetDeadline(time.Now().Add(socksTimeout))
err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
// Disable deadline.
conn.SetDeadline(time.Time{})
Log("SOCKS request for %s", dest)
destAddr, err := net.ResolveTCPAddr("tcp", dest)
if err != nil {
return nil, err
}
wsUrl := url.URL{Scheme: "ws", Host: dest}
ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
if err != nil {
return nil, err
}
Log("WebSocket connection to %s", ws.Config().Location.String())
return destAddr, nil
})
if err != nil {
return err
}
defer ws.Close()
proxy(conn, ws)
return nil
}
示例2: send
func send(tcpconn *net.TCPConn, rsp *Response) (err error) {
Len := uint32(PkgLenSize) + uint32(len(rsp.Head)) + uint32(len(rsp.Body))
Hlen := uint16(Uint16Size) + uint16(len(rsp.Head))
data := make([]byte, 0, int(Len)) // len:0, cap:Len; TODO(zog): cache
buf := bytes.NewBuffer(data) // TODO(zog): 复用
binary.Write(buf, binary.BigEndian, Len)
binary.Write(buf, binary.BigEndian, Hlen)
buf.Write(rsp.Head)
buf.Write(rsp.Body)
if debug {
glog.Infof("sent bytes to %s, len: %d",
tcpconn.RemoteAddr().String(), len(buf.Bytes()))
glog.Flush()
}
tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond))
if _, err = tcpconn.Write(buf.Bytes()); err != nil {
return err
}
if debug {
glog.Infof("sent data(len:%d): %v", buf.Len(), buf.Bytes())
glog.Flush()
}
return nil
}
示例3: newRCConn
func newRCConn(c *net.TCPConn, iface *Interface) (*RCConn, error) {
// Leave enough room in the completion queue for any operation,
// including inline sends, to return an error. CQ overruns
// sometimes cause internal errors in the HCA, which can make the
// kernel very unhappy.
qp, err := iface.NewQueuePair(10)
if err != nil {
return nil, err
}
if err := c.SetDeadline(ioDeadline()); err != nil {
checkClose(qp)
return nil, err
}
destLid, destQpn, destPsn, err := writeReadQPParams(c, iface.Lid(), qp.Qpn(), qp.Psn())
if err != nil {
checkClose(qp)
return nil, err
}
messages, meta := CreateBuffers()
if err := qp.Setup(destLid, destQpn, destPsn, messages); err != nil {
checkClose(qp)
return nil, err
}
laddr, raddr := c.LocalAddr(), c.RemoteAddr()
rcc := &RCConn{iface, laddr, raddr, qp, math.MaxInt64, true, messages, meta, false}
return rcc, nil
}
示例4: recv
func recv(uid int64, gid int64, conn *net.TCPConn) {
seq := 1
n := count * (concurrent)
total := n
for i := 0; i < n; i++ {
conn.SetDeadline(time.Now().Add(40 * time.Second))
msg := ReceiveMessage(conn)
if msg == nil {
log.Println("receive nill message")
total = i
break
}
if msg.cmd != MSG_GROUP_IM {
log.Println("mmmmmm:", Command(msg.cmd))
i--
}
if msg.cmd == MSG_GROUP_IM {
//m := msg.body.(*IMMessage)
//log.Printf("sender:%d receiver:%d content:%s", m.sender, m.receiver, m.content)
}
seq++
ack := &Message{MSG_ACK, seq, DEFAULT_VERSION, &MessageACK{int32(msg.seq)}}
SendMessage(conn, ack)
}
log.Printf("%d received:%d", uid, total)
c <- true
}
示例5: dialToPipe
func (t *TCPProxy) dialToPipe(ctx context.Context, client *net.TCPConn) {
svConn, err := t.openSvConn()
if err != nil {
log.Println(err)
closeConn(client)
return
}
deadline := time.Now().Add(t.PipeDeadLine)
printErr(log.Println, svConn.SetDeadline(deadline))
printErr(log.Println, client.SetDeadline(deadline))
errSv2Cl := pipe(client, svConn)
errCl2Sv := pipe(svConn, client)
select {
case err = <-errCl2Sv:
case err = <-errSv2Cl:
case <-ctx.Done():
}
if err != nil && err != io.EOF {
log.Printf("pipe err:%s addr:%s", err, t.DialAddr)
}
closeConn(client)
closeConn(svConn)
//残ったメッセージを読み捨てる
for range errCl2Sv {
}
for range errSv2Cl {
}
}
示例6: 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)
}
}
}
示例7: sendData
func (s Sender) sendData(data []byte, conn *net.TCPConn) bool {
if len(data) == 0 {
return true
}
if conn == nil {
return false
}
/*
lenBuf := make([]byte, 4)
nData := len(data)
binary.PutUvarint(lenBuf, uint64(nData))
data = append(lenBuf, data...)
*/
st := time.Now()
packId := tcp_pack.GetPackId(data)
conn.SetDeadline(time.Now().Add(5 * time.Minute)) //设置超时
loglib.Info(fmt.Sprintf("sender%d start sending pack:%s length:%d", s.id, packId, len(data)))
n, err := conn.Write(data)
ed := time.Now()
loglib.Info(fmt.Sprintf("sender%d end sending pack:%s length:%d elapse:%s", s.id, packId, n, ed.Sub(st)))
lib.CheckError(err)
//写失败了就不用等应答了,肯定拿不到
if err == nil {
conn.SetReadDeadline(time.Now().Add(8 * time.Minute)) //设置超时
time1 := time.Now()
var temp []byte = make([]byte, 128)
count, err := conn.Read(temp)
if err == nil {
loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s", s.id, count, packId, time.Now().Sub(time1)))
} else {
loglib.Info(fmt.Sprintf("sender%d get anwser data len:%d for pack:%s elapse:%s, error:%s", s.id, count, packId, time.Now().Sub(time1), err.Error()))
}
temp = temp[:count]
if string(temp) == "ok" { //发送成功
return true
} else if string(temp) == "wrong header" {
//包头错误,丢弃
loglib.Info(packId + " has wrong header, retry later!")
return false
} else { //发送失败
//报警
return false
}
} else {
loglib.Warning(fmt.Sprintf("write pack %s error:%s", packId, err.Error()))
}
return false
}
示例8: handleConn
func handleConn(conn *net.TCPConn, resp responses) {
defer conn.Close()
p := &peerState{}
p.ipPort = ipPort(conn.RemoteAddr().String())
for {
conn.SetDeadline(time.Now().Add(connectionTimeout))
m, err := readMessage(conn)
if err != nil {
log.Println("handleConn:", err)
resp.delNodeChan <- p.ipPort.toNetworkAddress()
return
}
command := m.h.command
log.Printf("got command: %v", command)
switch command {
case "version":
err = handleVersion(conn, p, m, resp.addNodeChan)
case "addr":
err = handleAddr(conn, p, m, resp.addrsChan)
case "verack":
err = handleVerack(conn, p, resp.addNodeChan)
case "inv":
err = handleInv(conn, p, m, resp.invChan)
case "msg":
err = handleMsg(conn, p, m, resp.msgChan)
case "broadcast":
err = handleBroadcast(conn, p, m, resp.broadcastChan)
default:
// XXX
err = fmt.Errorf("ignoring unknown command %q", command)
log.Println(err.Error())
err = nil
}
// The handler functions must be able to run concurrenly, so don't use
// m after calling the functions above.
if err != nil {
log.Printf("error while processing command %v: %v", command, err)
resp.delNodeChan <- ipPort(conn.RemoteAddr().String()).toNetworkAddress()
// Disconnects from node.
return
}
}
}
示例9: serve
func (s *Service) serve(conn *net.TCPConn) {
defer conn.Close()
defer s.waitGroup.Done()
for {
select {
case <-s.ch:
return
default:
}
conn.SetDeadline(time.Now().Add(1e9))
buf := make([]byte, 4096)
readCount, err := conn.Read(buf)
if err != nil {
break
}
s.receivedChan <- buf[:readCount]
}
}
示例10: readDiamondMetrics
// readDiamondMetrics reads from the connection
func (d Diamond) readDiamondMetrics(conn *net.TCPConn) {
defer conn.Close()
conn.SetKeepAlive(true)
conn.SetKeepAlivePeriod(time.Second)
reader := bufio.NewReader(conn)
log.Info("Diamond collector connection started: ", conn.RemoteAddr())
for {
// TODO: verify that timeout is actually working.
conn.SetDeadline(time.Now().Add(1e9))
line, err := reader.ReadBytes('\n')
if err != nil {
break
}
log.Debug("Read from Diamond collector: ", string(line))
d.incoming <- line
}
log.Info("Diamond collector connection closed: ", conn.RemoteAddr())
}
示例11: recv
func recv(tcpconn *net.TCPConn) (req *Request, err error) {
// TODO(zog): 用 bytes.Buffer 优化
var Len uint32
var Hlen uint16
tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond)) // TODO(zog): is 100ms good?
if err = binary.Read(tcpconn, binary.BigEndian, &Len); err != nil {
return nil, err
}
if int(Len) < MinAllowedPkgLen || int(Len) > MaxAllowedPkgLen {
err = fmt.Errorf("invalid package len: Len=%d(min:%d, max:%d)",
Len, MinAllowedPkgLen, MaxAllowedPkgLen)
return nil, err
}
data := make([]byte, int(Len)-Uint32Size) // TODO(zog): cache
tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond))
if n, rerr := io.ReadFull(tcpconn, data); err != nil {
err = fmt.Errorf("read package data n:%d(expect:%d), err: %s",
n, len(data), rerr)
return nil, err
}
Hlen = (uint16(data[1]) | uint16(data[0])<<8)
if (int(Hlen) < MinAllowedPkgTotalHeadLen) ||
(int(Hlen) > MaxAllowedPkgTotalHeadLen) ||
(int(Hlen) > len(data)-MinAllowedPkgBodyLen) {
err = fmt.Errorf("invalid Hlen: %d, (min:%d, max:%d), over expect max: %d",
Hlen, MinAllowedPkgTotalHeadLen, MaxAllowedPkgTotalHeadLen, len(data))
return nil, err
}
if debug {
glog.Infof("Len:%d, Hlen:%d, len(data):%d, data:%v",
Len, Hlen, len(data), data)
glog.Flush()
}
return &Request{
Head: data[2 : 2+(Hlen-2)],
Body: data[2+(Hlen-2):],
}, nil
}
示例12: receiveMessages
func (t *TCPInput) receiveMessages(conn *net.TCPConn, messageReader rowmessage.MessageReader) {
errCount := 0
msgCount := 0
defer conn.Close()
defer func() {
log.Printf("TCPInput.receiveMessages: total=%d", msgCount)
}()
for {
conn.SetDeadline(time.Now().Add(TCPInputTimeout))
msg, err := messageReader.ReadMsg()
if err != nil {
if err == io.EOF {
log.Printf("TCPInput.receiveMessages: EOF!")
return
}
netErr, ok := err.(net.Error)
if ok {
if netErr.Timeout() && !netErr.Temporary() {
log.Printf("TCPInput.receiveMessages: timeout conn=%v", conn)
return
}
errCount++
if errCount > TCPMaxErrors {
log.Printf("TCPInput.receiveMessages: max errors reached err=%s", msg, err)
return
}
}
log.Printf("TCPInput.receiveMessages: error=%s", err)
continue
}
errCount = 0
// log.Printf("TCPInput.receiveMessages: msg=%v err=%s", msg, err)
t.messages <- msg
msgCount++
}
}
示例13: connectionHandler
func connectionHandler(conn *net.TCPConn, out chan *oakmole.Record) {
defer conn.Close()
timeBegin := time.Now()
conn.SetKeepAlive(false)
conn.SetLinger(0)
conn.SetDeadline(timeBegin.Add(IOTimeout))
addrLocal := conn.LocalAddr().(*net.TCPAddr)
addrRemote := conn.RemoteAddr().(*net.TCPAddr)
log.Println("New connection from", addrRemote)
// TODO: reuse existing buffers
buffer := make([]byte, ReadBufferSize)
var httpRequest *http.Request
totalSize := 0
for i := 1; i <= 3 && totalSize < ReadBufferSize; i++ {
size, err := conn.Read(buffer[totalSize:])
totalSize += size
if err == io.EOF {
break
}
if err != nil {
// Only log IO timeout on first Read().
// Later it just means that client already sent everything.
if netErr, ok := err.(net.Error); i == 1 || !ok || !netErr.Timeout() {
log.Println("Read: try:", i, "local:", addrLocal, "remote:", addrRemote, "error:", err)
}
if i == 1 {
return
}
break
}
// Try to parse HTTP request.
// This allows to stop reading from socket early.
// TODO: reuse existing bufio.Reader
bufReader := bufio.NewReader(bytes.NewReader(buffer))
httpRequest, err = http.ReadRequest(bufReader)
httpRequest.Body.Close()
if err == nil {
break
} else {
httpRequest = nil
}
}
buffer = buffer[:totalSize]
record := &oakmole.Record{
Timestamp: uint64(timeBegin.UnixNano() / 1000),
LocalIP: addrLocal.IP,
RemoteIP: addrRemote.IP,
Body: buffer,
}
if httpRequest != nil {
record.HttpHost = []byte(httpRequest.Host)
} else {
record.HttpHost = readHost(buffer)
}
// log.Println("Read: success local:", addrLocal, "remote:", addrRemote, "size:", totalSize, "first bytes:", string(buffer[:20]))
// t1 := time.Now()
out <- record
// outSendTime := time.Now().Sub(t1)
// log.Println("connectionHandler: out<- time:", outSendTime)
if httpRequest != nil && httpRequest.Method == "GET" && httpRequest.RequestURI == "/robots.txt" {
conn.Write(robotsDisallowBytes)
}
}
示例14: send
func send(uid int64, gid int64, conn *net.TCPConn) {
ack_c := make(chan int, 100)
close_c := make(chan bool)
seq := 1
go func() {
c := count * (concurrent - 1)
total := c
for i := 0; i < c; i++ {
conn.SetDeadline(time.Now().Add(40 * time.Second))
msg := ReceiveMessage(conn)
if msg == nil {
log.Println("receive nill message")
total = i
break
}
if msg.cmd == MSG_ACK {
i--
ack_c <- 0
continue
}
if msg.cmd != MSG_GROUP_IM {
log.Println("mmmmmm:", Command(msg.cmd))
i--
}
if msg.cmd == MSG_GROUP_IM {
//m := msg.body.(*IMMessage)
//log.Printf("sender:%d receiver:%d content:%s", m.sender, m.receiver, m.content)
}
seq++
ack := &Message{MSG_ACK, seq, DEFAULT_VERSION, &MessageACK{int32(msg.seq)}}
SendMessage(conn, ack)
}
log.Printf("%d received:%d", uid, total)
close(close_c)
}()
for i := 0; i < count; i++ {
content := fmt.Sprintf("test....%d", i)
seq++
msg := &Message{MSG_GROUP_IM, seq, DEFAULT_VERSION, &IMMessage{uid, gid, 0, int32(i), content}}
SendMessage(conn, msg)
var e bool
select {
case <-ack_c:
case <-close_c:
for {
ack := ReceiveMessage(conn)
if ack == nil {
e = true
break
}
if ack.cmd == MSG_ACK {
break
}
}
}
if e {
break
}
}
<-close_c
conn.Close()
log.Printf("%d send complete", uid)
c <- true
}
示例15: CheckStatusOldConn
func CheckStatusOldConn(conn *net.TCPConn, host string, port uint16) (*MinecraftStatus, time.Duration, error) {
buff := &bytes.Buffer{}
buff.Grow(512)
buff.Write([]byte{0xFE, 0x01, 0xFA})
buff.Write(pack_utf16be("MC|PingHost"))
hostpacked := pack_utf16be(host)
binary.Write(buff, binary.BigEndian, int16(len(hostpacked)+5)) // host + uint8 protocol + int32 port
binary.Write(buff, binary.BigEndian, uint8(LAST_OLD_PROTOCOL))
buff.Write(hostpacked)
binary.Write(buff, binary.BigEndian, int32(port))
conn.SetDeadline(time.Now().Add(DEADLINE))
_, err := conn.Write(buff.Bytes())
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error sending: %s", err)
}
t1 := time.Now()
var c [1]byte
_, err = conn.Read(c[:])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error reading packet id: %s", err)
}
if c[0] != 0xFF {
return nil, 0, fmt.Errorf("CheckStatusOld bad response packet id: %d", c[0])
}
msg, err := read_utf16be(conn, 512)
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error reading response string: %s", err)
}
// TODO: zastanowic sie czy nie lepiej uzyc fmt.Sscanf
status := &MinecraftStatus{}
if strings.HasPrefix(msg, "§1") { // 1.4 +
params := strings.Split(msg, "\x00")
if len(params) != 6 {
return nil, 0, fmt.Errorf("CheckStatusOld bad param count %d (1)", len(params))
}
status.ProtocolVersion, err = strconv.Atoi(params[1])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error converting protocol version")
}
status.GameVersion = params[2]
status.Description = params[3]
status.Players, err = strconv.Atoi(params[4])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error converting player count")
}
status.Slots, err = strconv.Atoi(params[5])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error converting slot count")
}
} else { // < 1.4
params := strings.Split(msg, "§")
if len(params) != 3 {
return nil, 0, fmt.Errorf("CheckStatusOld bad param count %d (2)", len(params))
}
// last protocol and game version with this response format
status.ProtocolVersion = 39
status.GameVersion = "1.3.1"
status.Description = params[0]
status.Players, err = strconv.Atoi(params[1])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error converting player count")
}
status.Slots, err = strconv.Atoi(params[2])
if err != nil {
return nil, 0, fmt.Errorf("CheckStatusOld error converting slot count")
}
}
return status, time.Since(t1), nil
}