数据未通过通道发送

huangapple go评论91阅读模式
英文:

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

你有两个问题:

  1. 在handleClient中的buf为空。
  2. 发送方和接收方之间存在死锁。

第一个问题很简单 - 只需使用"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:

  1. Empty buf in handleClient
  2. 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 &lt;- buf[0:n]
fmt.Println(mesg)
ind &lt;- n 
fmt.Println(ind)

So you send the message first and then - message length. But on receiver side you have:

n := &lt;-ind
fmt.Println(&quot;N recieved&quot;)
buf := &lt;-mesg
fmt.Println(&quot;Channels recieved&quot;)

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 &lt;- n
mesg &lt;- buf[0:n]
fmt.Println(mesg)
fmt.Println(ind)

huangapple
  • 本文由 发表于 2014年1月9日 04:59:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/21006391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定