4
我正在嘗試學習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)
}
}
我得到以下輸出從這個函數:
[[email protected] ~/src/go/echo_server] ./6.out 1234
Using port 1234
Wrote 17 bytes to socket
Error when reading from socket: EOF
這是我看到在客戶端上:
[[email protected] ~] 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.
任何幫助,將不勝感激(或指針資源;關於套接字API的go文檔留下了一些不足之處)。
感謝,
彌敦道
這樣做,謝謝! 我想我還沒有完全理解切片......我會再讀一遍。 – Nathan 2010-02-16 15:11:24