我正在尝试学习go语言,而我正在编写一个简单的echo服务器.但是,我很难让它工作.
func listen(server string) {
var buf []byte
listener, ok := net.Listen("tcp", server)
if ok != nil {
fmt.Fprintf(os.Stderr, "Could not listen on socket: %s\n", ok.String())
return
}
conn, ok := listener.Accept()
if ok != nil {
fmt.Fprintf(os.Stderr, "Could not accept connection on socket: %s\n", ok.String())
return
}
writelen, ok := conn.Write(strings.Bytes("Ready to receive\n"))
if ok != nil {
fmt.Fprintf(os.Stderr, "Could not write to socket: %s\n", ok.String())
} else {
fmt.Printf("Wrote %d bytes to socket\n", writelen)
}
for ;; {
readlen, ok := conn.Read(buf)
if ok != nil {
fmt.Fprintf(os.Stderr, "Error when reading from socket: %s\n", ok.String())
return
}
if readlen == 0 {
fmt.Printf("Connection closed by remote host\n")
return
}
fmt.Printf("Client at %s says '%s'\n", conn.RemoteAddr().String(), buf)
}
}
Run Code Online (Sandbox Code Playgroud)
我从这个函数得到以下输出:
[nathan@ebisu ~/src/go/echo_server] ./6.out 1234
Using port 1234
Wrote 17 bytes to socket
Error when reading from socket: EOF
Run Code Online (Sandbox Code Playgroud)
这是我在客户端看到的:
[nathan@ebisu ~] telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Ready to receive
Connection closed by foreign host.
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激(或指向资源的指针;套接字API上的go文档留下了一些不足之处).
谢谢,
弥敦道
在您的示例中,buf需要具有确定的大小.您已将其声明为0长度切片.
声明为:
var buf = make([]byte, 1024)
Run Code Online (Sandbox Code Playgroud)