我正在嘗試學習Go語言,并且正在編寫一個簡單的回顯服務器。不過,我很難使它正常工作。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) }}我從此函數獲得以下輸出:[nathan@ebisu ~/src/go/echo_server] ./6.out 1234Using port 1234Wrote 17 bytes to socketError when reading from socket: EOF這是我在客戶端上看到的:[nathan@ebisu ~] telnet 127.0.0.1 1234Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is '^]'.Ready to receiveConnection closed by foreign host.任何幫助將不勝感激(或指向資源的指針;套接字API上的go文檔尚有待改進)。
- 2 回答
- 0 關注
- 268 瀏覽
添加回答
舉報
0/150
提交
取消