本文整理汇总了Golang中net.Conn.SetDeadline方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.SetDeadline方法的具体用法?Golang Conn.SetDeadline怎么用?Golang Conn.SetDeadline使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.Conn
的用法示例。
在下文中一共展示了Conn.SetDeadline方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: threadedAcceptConn
// threadedAcceptConn adds a connecting node as a peer.
func (g *Gateway) threadedAcceptConn(conn net.Conn) {
if g.threads.Add() != nil {
conn.Close()
return
}
defer g.threads.Done()
conn.SetDeadline(time.Now().Add(connStdDeadline))
addr := modules.NetAddress(conn.RemoteAddr().String())
g.log.Debugf("INFO: %v wants to connect", addr)
remoteVersion, err := acceptConnVersionHandshake(conn, build.Version)
if err != nil {
g.log.Debugf("INFO: %v wanted to connect but version handshake failed: %v", addr, err)
conn.Close()
return
}
if build.VersionCmp(remoteVersion, handshakeUpgradeVersion) < 0 {
err = g.managedAcceptConnOldPeer(conn, remoteVersion)
} else {
err = g.managedAcceptConnNewPeer(conn, remoteVersion)
}
if err != nil {
g.log.Debugf("INFO: %v wanted to connect, but failed: %v", addr, err)
conn.Close()
return
}
// Handshake successful, remove the deadline.
conn.SetDeadline(time.Time{})
g.log.Debugf("INFO: accepted connection from new peer %v (v%v)", addr, remoteVersion)
}
示例2: handleGraphiteTextProtocol
// Handles incoming requests for both TCP and UDP
func handleGraphiteTextProtocol(t *trTransceiver, conn net.Conn, timeout int) {
defer conn.Close() // decrements tcpWg
if timeout != 0 {
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
}
// We use the Scanner, becase it has a MaxScanTokenSize of 64K
connbuf := bufio.NewScanner(conn)
for connbuf.Scan() {
packetStr := connbuf.Text()
if dp, err := parseGraphitePacket(packetStr); err != nil {
log.Printf("handleGraphiteTextProtocol(): bad backet: %v")
} else {
t.queueDataPoint(dp)
}
if timeout != 0 {
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
}
}
if err := connbuf.Err(); err != nil {
log.Println("handleGraphiteTextProtocol(): Error reading: %v", err)
}
}
示例3: handleCient
func handleCient(conn net.Conn) {
conn.SetDeadline(time.Now().Add(2 * time.Minute))
request := make([]byte, 128)
defer conn.Close()
for {
read_len, err := conn.Read(request)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s", err)
break
}
fmt.Printf(string(read_len))
// if read_len == 0 {
// break
// } else if string(request) == "timestamp" {
daytime := time.Now().String()
conn.Write([]byte(daytime))
// }
}
request = make([]byte, 128)
}
示例4: Handler
// 客户端连接的处理逻辑。 首先握手,握手失败关闭连接;然后读数据,写入 Dispatcher 的处理队列。
func Handler(conn net.Conn, hsPwd string, inputChid string) {
defer conn.Close()
chid := ""
if len(inputChid) < 1 {
ch, recvers, err := HandShake(conn, hsPwd)
if err != nil {
return
}
chid = ch
createConnQ <- &ConnInfo{conn, chid, 600, recvers}
} else {
chid = inputChid
createConnQ <- &ConnInfo{conn, chid, 0, nil}
}
for {
data := make([]byte, 1048576)
n, err := conn.Read(data) // 读出数据,放入 Dispatcher 的发送队列
if err != nil { // 关闭时给 Dispatcher 发送通知
if err == io.EOF {
log.Println("Connection closed!")
} else {
log.Println("Read error: ", err)
}
removeConnQ <- chid
break
}
conn.SetDeadline(time.Now().Add(time.Duration(120) * time.Second))
log.Println("Read data:", string(data[:n]))
sendQ <- SendQEle{chid, bytes.NewBuffer(data[:n])}
}
}
示例5: proxyClient
// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, timeout time.Duration) {
defer svrConn.Close()
var buffer [4096]byte
for {
n, err := svrConn.Read(buffer[0:])
if err != nil {
if !logTimeout(err) {
glog.Errorf("Read failed: %v", err)
}
break
}
svrConn.SetDeadline(time.Now().Add(timeout))
if err != nil {
glog.Errorf("SetDeadline failed: %v", err)
break
}
n, err = udp.WriteTo(buffer[0:n], cliAddr)
if err != nil {
if !logTimeout(err) {
glog.Errorf("WriteTo failed: %v", err)
}
break
}
}
activeClients.mu.Lock()
delete(activeClients.clients, cliAddr.String())
activeClients.mu.Unlock()
}
示例6: handleMessage
func (p *Proxy) handleMessage(h *messageHeader, client, server net.Conn) error {
deadline := time.Now().Add(p.messageTimeout)
server.SetDeadline(deadline)
client.SetDeadline(deadline)
if h.OpCode == OpQuery {
return p.handleQueryRequest(h, client, server)
}
if err := h.WriteTo(server); err != nil {
log.Println(err)
return err
}
if _, err := io.CopyN(server, client, int64(h.MessageLength-headerLen)); err != nil {
log.Println(err)
return err
}
if h.OpCode.HasResponse() {
if err := copyMessage(client, server); err != nil {
log.Println(err)
return err
}
}
return nil
}
示例7: serveConn
// called in a go statement
func serveConn(conn net.Conn, stmt *sql.Stmt) {
defer conn.Close()
log.Print(conn.RemoteAddr(), " connected to server...")
ret := make([]byte, 1500)
conn.SetDeadline(time.Now().Add(10 * time.Second))
n, err := conn.Read(ret)
if err != nil {
log.Print("error in reading: ", err)
return
}
var cmds []interface{}
err = json.Unmarshal(ret[:n], &cmds)
if err != nil {
log.Print("Fail to parse results")
return
}
if _, ok := cmds[0].(string); !ok {
log.Print("error in serveConn, data format that clients send is wrong")
return
}
cmd := cmds[0].(string)
switch cmd {
case "INIT":
initNode(conn, stmt)
case "MONITOR":
parseResults(cmds)
default:
log.Print("Unknown command: ", cmds)
}
}
示例8: Handle
// Handle triggers the collect-metrics hook and writes collected metrics
// to the specified connection.
func (l *handler) Handle(c net.Conn) (err error) {
defer func() {
if err != nil {
fmt.Fprintf(c, "%v\n", err.Error())
} else {
fmt.Fprintf(c, "ok\n")
}
c.Close()
}()
// TODO(fwereade): 2016-03-17 lp:1558657
err = c.SetDeadline(time.Now().Add(spool.DefaultTimeout))
if err != nil {
return errors.Annotate(err, "failed to set the deadline")
}
recorder, err := l.config.metricsFactory.Recorder(
l.config.validMetrics,
l.config.charmURL.String(),
l.config.unitTag.String(),
)
if err != nil {
return errors.Annotate(err, "failed to create the metric recorder")
}
defer recorder.Close()
err = l.config.runner.do(recorder)
if err != nil {
return errors.Annotate(err, "failed to collect metrics")
}
return nil
}
示例9: RecvData
// RecvData receives data over network connection (stream-oriented).
func RecvData(conn net.Conn, data []byte, srv string) (int, bool) {
for retry := 0; retry < retries; {
// set timeout
conn.SetDeadline(time.Now().Add(timeout))
// read data from socket buffer
n, err := conn.Read(data)
if err != nil {
// handle error condition
switch err.(type) {
case net.Error:
// network error: retry...
nerr := err.(net.Error)
if nerr.Timeout() {
return 0, true
} else if nerr.Temporary() {
retry++
time.Sleep(delay)
continue
}
default:
logger.Printf(logger.INFO, "[%s] Connection closed by peer\n", srv)
return 0, false
}
}
// report success
if retry > 0 {
logger.Printf(logger.INFO, "[%s] %d retries needed to receive data.\n", srv, retry)
}
return n, true
}
// retries failed
logger.Printf(logger.ERROR, "[%s] Read failed after retries...\n", srv)
return 0, false
}
示例10: handle
func handle(conn net.Conn) {
defer conn.Close()
err := conn.SetDeadline(time.Now().Add(Timeout))
if err != nil {
log.Errorf("Error setting deadline on conn")
return
}
buf := getBuf(bufSize)
defer putBuf(buf)
n, err := conn.Read(buf)
if err != nil {
log.Error("Error reading from conn")
return
}
log.Printf("Got %+q", buf[:n])
resp, err := parseRequest(buf[:n])
if err != nil {
log.Error(err)
return
}
n, err = conn.Write(resp)
if err != nil || n != len(resp) {
log.Errorf("Error writing to conn")
return
}
}
示例11: handleConn
// TODO: maintain compatibility
func (h *Host) handleConn(conn net.Conn) {
defer conn.Close()
// Set an initial duration that is generous, but finite. RPCs can extend
// this if so desired.
conn.SetDeadline(time.Now().Add(5 * time.Minute))
var id types.Specifier
if err := encoding.ReadObject(conn, &id, 16); err != nil {
return
}
var err error
switch id {
case modules.RPCSettings:
err = h.rpcSettings(conn)
case modules.RPCUpload:
err = h.rpcUpload(conn)
case modules.RPCRevise:
err = h.rpcRevise(conn)
case modules.RPCDownload:
err = h.rpcDownload(conn)
default:
h.log.Printf("WARN: incoming conn %v requested unknown RPC \"%v\"", conn.RemoteAddr(), id)
return
}
if err != nil {
h.log.Printf("WARN: incoming RPC \"%v\" failed: %v", id, err)
}
}
示例12: request
func (ctr *Controller) request(conn net.Conn) (err error) {
log.Print("ctr.request:")
var iniStr = []interface{}{"INIT"}
sends, err := json.Marshal(iniStr)
if err != nil {
log.Print("error in request: ", err)
return
}
_, err = conn.Write(sends) // fisrt send the INIT and local addr to it
if err != nil {
log.Print("conn.Write(): ", err)
return
}
conn.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))
defer func() {
var zero time.Time
conn.SetDeadline(zero)
}()
ret := make([]byte, 1500)
n, err := conn.Read(ret)
if err != nil {
log.Print("conn.Read(): ", err)
return
}
id := -1
err = json.Unmarshal(ret[:n], &id) // fetch id
if err != nil {
log.Print("Fail to communicate with server: ", err)
return
}
ctr.id = id
go ctr.Listen(ctr.QUIT)
return nil
}
示例13: authorize
func authorize(conn net.Conn) bool {
tlsConn, ok := conn.(*tls.Conn)
if !ok {
return false
}
// Force handshake. Handshake usually happens on first read/write, but
// we want to authenticate before reading/writing so we need to force
// the handshake to get the client cert. If handshake blocks for more
// than the timeout, we kill the connection.
timer := time.AfterFunc(*timeoutDuration, func() {
logger.Printf("timed out TLS handshake on %s", conn.RemoteAddr())
conn.SetDeadline(time.Now())
conn.Close()
timeoutCounter.Inc(1)
})
err := tlsConn.Handshake()
timer.Stop()
if err != nil {
logger.Printf("failed TLS handshake on %s: %s", conn.RemoteAddr(), err)
errorCounter.Inc(1)
return false
}
return authorized(tlsConn.ConnectionState())
}
示例14: readFromConnection
func (cons *Socket) readFromConnection(conn net.Conn) {
defer func() {
conn.Close()
cons.WorkerDone()
}()
conn.SetDeadline(time.Time{})
buffer := shared.NewBufferedReader(socketBufferGrowSize, cons.flags, cons.offset, cons.delimiter)
for !cons.quit {
err := buffer.ReadAll(conn, cons.Enqueue)
// Handle errors
if err != nil && err != io.EOF {
if cons.clientDisconnected(err) {
return // ### return, connection closed ###
}
Log.Error.Print("Socket read failed: ", err)
continue // ### continue, keep open, try again ###
}
// Send ack if everything was ok
if cons.acknowledge != "" {
fmt.Fprint(conn, cons.acknowledge)
}
}
}
示例15: HandleClient
// HandleClient relays a message read from client connection c to mixnet
// connection d and relay reply.
func (p *ProxyContext) HandleClient(c net.Conn, d *Conn) error {
msg := make([]byte, MaxMsgBytes)
c.SetDeadline(time.Now().Add(p.timeout))
bytes, err := c.Read(msg)
if err != nil {
return err
}
if err = p.SendMessage(d, msg[:bytes]); err != nil {
return err
}
reply, err := p.ReceiveMessage(d)
if err != nil {
return err
}
c.SetDeadline(time.Now().Add(p.timeout))
if _, err = c.Write(reply); err != nil {
return err
}
return nil
}