Golang Go语言中用go实现socket,帮忙看看问题处在哪里
Golang Go语言中用go实现socket,帮忙看看问题处在哪里
package main
import (
“bytes”
“fmt”
“net”
“time”
)
func main() {
listener, err := net.Listen(“tcp”, “127.0.0.1:9527”)
defer listener.Close()
if err != nil {
fmt.Printf(“server err %v\n”, err)
} else {
for {
conn, err := listener.Accept()
if err == nil {
go handleConn(conn)
}
}
}
}
func Read(conn net.Conn) (string, error) {
readBytes := make([]byte, 1)
var buf bytes.Buffer
for {
_, err := conn.Read(readBytes)
if err != nil {
return “”, err
}
readByte := readBytes[0]
if readByte == ‘\t’ {
break
}
}
return buf.String(), nil
}
func Write(conn net.Conn, content string) (int, error) {
var buf bytes.Buffer
buf.WriteString(content)
buf.WriteByte(’\t’)
return conn.Write(buf.Bytes())
}
func handleConn(conn net.Conn) {
for {
conn.SetReadDeadline(time.Now().Add(2))
if str, err := Read(conn); err == nil {
fmt.Printf(“收到的数据:%v\n”, str)
Write(conn, “server got:”+str)
}else{
fmt.Printf(“read err: %v\n”,err)
}
}
}
现在用 telnet 发送消息,然后报错 read err: read tcp 127.0.0.1:9527->127.0.0.1:56508: i/o timeout
更多关于Golang Go语言中用go实现socket,帮忙看看问题处在哪里的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html