英文:
Data not being sent over channels
问题
我这里有这段代码:
https://gist.github.com/ChasingLogic/8324442
我正在尝试使用Golang学习网络编程,这是我第一次尝试并发编程,目标是创建一个简化版的IRC服务器,其中消息会发送并回显给所有连接的客户端。
但是不知何故,我的代码在将数据发送到通道后就无法继续执行了。如果我在代码中加入错误检查,它就会无限地输出EOF。
英文:
I have this code here
https://gist.github.com/ChasingLogic/8324442
I'm trying to learn network programming with Golang this is my first attempt at concurrency and the goal is the equivalent of a stripped down irc server where a message is sent and echoed to all connected clients.
For some reason my code never gets past sending the data into the channels. If I put an error check in it just infinitely spits out EOF.
答案1
得分: 3
你有两个问题:
- 在handleClient中的buf为空。
- 发送方和接收方之间存在死锁。
第一个问题很简单 - 只需使用"buf := make([]byte, 1024)"而不是"var buf []byte"。
第二个问题需要更详细的解释。
在handleClient中,你有以下代码:
fmt.Println(string(buf[0:n]))
mesg <- buf[0:n]
fmt.Println(mesg)
ind <- n
fmt.Println(ind)
所以你先发送消息,然后发送消息长度。但在接收方,你有以下代码:
n := <-ind
fmt.Println("N received")
buf := <-mesg
fmt.Println("Channels received")
所以你期望先接收消息长度,然后再接收消息本身。这样就会导致死锁:发送方在发送长度之前等待接收方接收消息,而接收方在接收消息长度之前等待接收消息。
只需更改handleClient的顺序,让它相反,问题就会解决:
fmt.Println(string(buf[0:n]))
ind <- n
mesg <- buf[0:n]
fmt.Println(mesg)
fmt.Println(ind)
英文:
You have two problems:
- Empty buf in handleClient
- Deadlock between sender and receiver
The first is easy - just use "buf := make([]byte, 1024)" instead of "var buf []byte".
The second one in more detail.
In handleClient you have
fmt.Println(string(buf[0:n]))
mesg <- buf[0:n]
fmt.Println(mesg)
ind <- n
fmt.Println(ind)
So you send the message first and then - message length. But on receiver side you have:
n := <-ind
fmt.Println("N recieved")
buf := <-mesg
fmt.Println("Channels recieved")
So you expect message length before the message itself. So there is a deadlock: the sender is waiting for someone to receive the message before sending the length but receiver is waiting to receive message length before receiving the message.
Just change handleClient to have the opposite order and it will work:
fmt.Println(string(buf[0:n]))
ind <- n
mesg <- buf[0:n]
fmt.Println(mesg)
fmt.Println(ind)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论