英文:
Server does not get message in a "Hello World" socket program
问题
我正在练习使用Unix套接字和bufio。这是程序:
// 注册服务器套接字
os.Remove("serversock")
socket, err := net.ListenUnix("unix", &net.UnixAddr{"serversock", "unix"})
if err != nil {
panic(err)
}
go func() {
for {
// 接受新连接
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("Got connection")
reader := bufio.NewReader(conn)
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("Got line", line)
}
}()
// 客户端连接
conn, err := net.DialUnix("unix", nil, &net.UnixAddr{"serversock", "unix"})
writer := bufio.NewWriter(conn)
n, err := writer.WriteString("hello world\n")
if err != nil {
panic(err)
}
fmt.Println("Written", n)
// 客户端等待
time.Sleep(1 * time.Second)
运行时,它会打印:
Written 13
Got connection
然后退出,所以服务器似乎没有收到消息。我做错了什么?
英文:
I am practicing to use Unix socket together with bufio. This is the program:
// Register server socket
os.Remove("serversock")
socket, err := net.ListenUnix("unix", &net.UnixAddr{"serversock", "unix"})
if err != nil {
panic(err)
}
go func() {
for {
// Accept new connection
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("Got connection")
reader := bufio.NewReader(conn)
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("Got line", line)
}
}()
// Client connection
conn, err := net.DialUnix("unix", nil, &net.UnixAddr{"serversock", "unix"})
writer := bufio.NewWriter(conn)
n, err := writer.WriteString("hello world\n")
if err != nil {
panic(err)
}
fmt.Println("Written", n)
// Client wait
time.Sleep(1 * time.Second)
When it runs, it prints:
Written 13
Got connection
And then exists, so the server does not seem to get the message. What did I do wrong?
答案1
得分: 1
你的写入器是有缓冲的,当你使用WriteString()
向其写入时,它不会立即刷新缓冲区。只需调用writer.Flush()
,它将实际发送该行。你也可以尝试直接向套接字写入并查看结果。
此外,你的接受循环应该像这样:
go func() {
for {
// 接受新连接
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("收到连接")
reader := bufio.NewReader(conn)
// 创建一个拥有读取循环的 goroutine
go func(reader *bufio.Reader) {
for {
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("收到行", line)
}
}(reader)
}
}()
英文:
Your writer is buffered, it doesn't flush the buffer when you WriteString()
to it. Simply call writer.Flush()
and it will actually send the line. You can also try writing directly to the socket and see what happens.
Also your accept loop should look like this:
go func() {
for {
// Accept new connection
conn, err := socket.Accept()
if err != nil {
panic(err)
}
fmt.Println("Got connection")
reader := bufio.NewReader(conn)
//spawn a goroutine that has a read loop
go func(reader *bufio.Reader) {
for {
line, err := reader.ReadString(byte('\n'))
if err != nil {
panic(err)
}
fmt.Println("Got line", line)
}
}(reader)
}
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论