【问题标题】:read udp [::]:4604: use of closed network connection读取 udp [::]:4604: 使用关闭的网络连接
【发布时间】:2021-01-25 00:47:51
【问题描述】:

我正在使用 UDP 服务器。在后台,服务器侦听actions,这是对客户端发送的数据包的抽象:

    go func() {
        for {
            buf := make([]byte, 1024)
            n, addr, err := PC.ReadFrom(buf)
            ClientAddresses[addr] = struct{}{}
            action := &service.Action{}
            proto.Unmarshal(buf[:n], action)
            Actions.InsertAction(action)
        }
    }()

客户端发送消息时,服务器将地址保存在一个集合中,如下图:

ClientAddresses[addr] = struct{}{}

服务器每 500 毫秒处理一次客户端发送的每个操作,并通过遍历地址集向客户端发送状态更改:

        for Changes.Len() > 0 {
            LogWhiteText("Sending state change:")
            LogPurpleText(Changes.GetChange())
            change := Changes.GetChange()
            for addr, _ := range ClientAddresses {
                SendChange(change, PC, addr)
            }
            Changes.RemoveChange()
        }
// SendChange sends an individual state change to a client
func SendChange(change *service.Change, pc net.PacketConn, addr net.Addr) {
    packet, err := proto.Marshal(change)
    if err != nil {
        LogRedText(err)
        return
    }
    pc.WriteTo(packet, addr)
}

在服务器启动并第一个客户端连接后,立即触发以下错误:

2020/10/10 01:39:48  Send state changes to the clients
2020/10/10 01:39:48  Sending state change:
2020/10/10 01:39:48  locationChange:{coordinate:{lng:12.476284  lat:41.91051}}
2020/10/10 01:39:48  read udp [::]:4604: use of closed network connection
panic: assignment to entry in nil map

我想就错误原因获得一些建议。正如错误所暗示的,连接已关闭,但我没有从客户端关闭它:

private UdpClient udpClient = new UdpClient();

    void onStart()
    {

        locationManager.onLocationChanged.AddListener(this.SendChangedLocation);
        try
        {
            udpClient.Connect("localhost", 4604);
            Coordinate coordinate = new Coordinate
            {
                Lng = (float)locationManager.currentLocation.longitude,
                Lat = (float)locationManager.currentLocation.latitude,
            };
            this.CreateNewCar(coordinate);
        }
        catch (Exception exc)
        {
            Debug.LogError(exc);
        }
    }

【问题讨论】:

  • 客户端代码正在关闭连接或应用程序正在终止(这也将关闭连接)。问题不在于发布的代码。问题出在调用 onStart 方法的代码中。
  • @jdweng 谢谢你的帮助。您可以将此作为答案发布吗?

标签: c# go server udp


【解决方案1】:

问题出在客户端。

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多