Golang 中国

客户端建立连接:

conn, err := net.DialTimeout("tcp", destIPPort, 3*time.Second)
if err != nil {
    Log(LL_INFO, "tcp connect error bef process log file, please check it.")
    return err
}
defer func() {
    if nil != conn {
        conn.Close()
    }
}()

客户端发送和接收:

scanner := bufio.NewScanner(file)
for scanner.Scan() {                
    line := scanner.Text()        
    index := strings.Index(line, "=")
    index = index + 1
    req := line[index:]
    //req = req + "\n"    //4post
    reqSent := []byte(req)                
    numSent, err := conn.Write(reqSent)
    ... //对err和numSent的异常处理
    conn.SetReadDeadline(time.Now().Add(3 * time.Second))
    numRecv, err := conn.Read(buff)
    if err != nil || numRecv < 0 {
        if err == io.EOF || err == syscall.EINVAL {                    
            Log(LL_INFO, "tcp connect is already closed.")
            return err
        }
        if 0 == numRecv {
            if nil != conn {
                conn.Close()
            }
            Log(LL_INFO,"4_post_log, err and numRecv: ", err, " . numRecv: ", numRecv)
            conn, err = net.DialTimeout("tcp", destIPPort, 6*time.Second)
            if err != nil {                        
                Log(LL_INFO, "tcp connect error:", err, ", please check it.")
                return err
            }                
        }else{                
            Log(LL_INFO, "tcp receive data error:", err, ", please check it.")
            return err
        }
    }
    Log(LL_INFO, "recv data:", string(buff[0:numRecv]))                            
}

server对端处理连接代码(echo发送收到的内容回去给客户端):

func handleConn(c net.Conn) {
    input := bufio.NewScanner(c)
    for input.Scan() {        
        lineRecv := input.Text()
        fmt.Println(lineRecv)
        fmt.Fprintln(c, lineRecv)        
    }
    c.Close()
}

如果我把“req = req + “\n””这行注释掉,不加\n在末尾,则报错超时“read tcp 127.0.0.1:35623->127.0.0.1:12345: i/o timeout”,收不到server端的数据:

2017-09-26 14:10:17 <LL_INFO> Data sent:hnd {1}Total sent 7bytes.
2017-09-26 14:10:17 <LL_INFO> Data sent finished, begin to recv...
2017-09-26 14:10:20 <LL_INFO> 4_post_log, err and numRecv: read tcp 127.0.0.1:35623->127.0.0.1:12345: i/o timeout . numRecv: 0
2017-09-26 14:10:23 <LL_INFO> recv data:

如果在末尾加上“\n”,则能收到server端echo回来的数据(如下是日志):

2017-09-26 13:53:12 <LL_INFO> Data sent:hnd {1}
Total sent 8bytes.
2017-09-26 13:53:12 <LL_INFO> Data sent finished, begin to recv...
2017-09-26 13:53:12 <LL_INFO> recv data:hnd {1}

jimyokl 于 2017-09-26 14:15 修改
2 回复
jimmykuu
#1 jimmykuu • 2017-09-27 11:01

这是服务器端用 Scanner 读取的问题,没有回车的话 Scan() 不返回。

一般可以这样操作:

buf := make([]byte, 1024)
n, err := conn.Read(buf)
525252
#2 525252 • 2017-10-05 16:46

for input.Scan() {

SCAN是指 line scan,碰到换行才认为是一个消息。

如果不使用\N,需要自己读buffer并检测是否是一个MSG结束。

需要 登录 后方可回复, 如果你还没有账号你可以 注册 一个帐号。

作者

发表话题