C# Sockets.BeginReceive Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gnome5482
    New Member
    • Mar 2008
    • 2

    C# Sockets.BeginReceive Problem

    I'm having a bit of trouble trying to receive packets from a remote server via udp.
    My application reads the data coming from the server and puts the data into a textbox. This seems to be working as I can see the scrollbar on the textbox move, but then the app just hangs. Here is my code:

    Code:
    Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                sck.Bind(new IPEndPoint(IPAddress.Any, 0));
                sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, 1);
                byte[] data = Encoding.Default.GetBytes("hello");
                sck.SendTo(data, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3137));
    
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                int bytesReceived = 0;
                byte[] recvBuffer = new byte[100 * 1024];
    
                do
                {
                    bytesReceived = sck.ReceiveFrom(recvBuffer, ref remoteEndPoint);
                    string response1 = Encoding.Default.GetString(recvBuffer, 0, bytesReceived);
                    string response2 = Regex.Replace(response1, "[\r\n]", Environment.NewLine);
                    textBox1.Text += response2;
                } while (bytesReceived > 0);
    I'm sure the problem is that I'm ending the loop improperly, but all of my attempts to fix this have failed. The packets that come back from the server are completely random in size and the content of the packets is always different, and there are always a random number of packets that will be returned. So I can't count packets, or rely on information in the packets, or rely on packet size to end the loop. Is there another way of doing this? Thanks for your time.
Working...