UDP套接字问题

时间:2012-03-26 15:26:57

标签: c# .net sockets udp udpclient

我的udp套接字有一个奇怪的问题。首先,让我为您提供代码:

服务器端:

        UdpClient udpClient = new UdpClient(UdpPort);

        udpClient.Connect(pendingClient.IpEndPoint, pendingClient.UdpPort);

        foreach (int frameNumber in pendingClient.FramesToSend)
        {
            byte[] frameBytes = ...
            udpClient.Send(frameBytes, frameBytes.Length);
        }
        udpClient.Close();

客户方:

 using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            socket.Bind(new IPEndPoint(IPAddress.Any, UdpPort));

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);

            Console.WriteLine("Receiving frames");
            while (!_sendingCompleted)
            {
                byte[] receive = new byte[Constants.FrameSize + Frame.HeaderSizeBytes];
                try
                {
                    socket.Receive(receive);
                }
                catch (SocketException exception)
                {
                    if (exception.SocketErrorCode == SocketError.TimedOut)
                    {
                        break;
                    }

                    throw;
                }
           ...
}

问题是:当我第一次从服务器发送到客户端时,一切都运行正常,但当我第二次(等等)时间 - 客户端什么都没收到。这个问题可能是什么原因,我该如何解决?

非常感谢。

1 个答案:

答案 0 :(得分:0)

看起来您没有在周期中接收数据,请尝试以下方法:

do 
{

  bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);

  page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);

} while (bytes > 0);