客户端建立连接:
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在末尾,则报错:
2017-09-26 13:36:03 <LL_INFO> 4_post_log, err and numRecv: read tcp 127.0.0.1:51863->127.0.0.1:12345: i/o timeout . numRecv: 0
如果在末尾加上“\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}
【请教】socket客户端conn.Write()发送的内容末尾加上\n就能得到server端回应,否则超时,请帮忙看看是客户端还是server端问题,先谢谢了
jimyokl · · 1155 次点击`bufio.NewScanner`创建的`Scanner`默认的分割函数是`ScanLines`,而`ScanLines`需要一个*必选*的*换行符*。[参考标准库中文版](https://studygolang.com/pkgdoc) [参考标准库英文文版](http://docs.studygolang.com/pkg/bufio/#NewScanner)
#4