Naveen

Naveen

  • 1.2k
  • 158
  • 11.8k

UDP Client not printing the received messages from udp server.

Oct 10 2024 9:49 AM
//UDP CLIENT
 private void ConnectUdp()
 {
     IPAddress serverIP = IPAddress.Parse("127.0.0.1");
     int serverPort = 8081;
     int localPort = 8080; // Port for receiving messages

     // Initialize and bind the UDP client
     _udpClient2 = new UdpClient(serverPort); // Bind to local port
     _udpClient2.Connect(serverIP, serverPort); // Connect to the server

     _udpclientConnected = true; // Set the connected flag
     AppendToReceivedMessages("Connected to server."); // Display connection message

     // Start receiving messages continuously
     Task.Run(() => ReceiveMessages());
 }

 private async Task ReceiveMessages()
 {
     try
     {
         // Continuously listen for messages
         while (_udpclientConnected) // Check if still connected
         {
             byte[] buffer = new byte[1024]; // Buffer to hold the incoming data

             IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // Local port is already bound

             // Receive messages asynchronously
             var receiveBytes = await _udpClient2.ReceiveAsync();

             // Pass the received data to your message handler
             _udpClient_MessageReceived(receiveBytes.Buffer);
         }
     }
     catch (Exception ex)
     {
         AppendToReceivedMessages($"Error receiving data: {ex.Message}");
     }
 }


 private void _udpClient_MessageReceived(byte[] bytes)
 {
     // Convert the received byte array to a string
     string receivedMessage = Encoding.ASCII.GetString(bytes);

     // Update the TextBox with the received message
     AppendToReceivedMessages(receivedMessage);
 }

I am trying to create a udp server, udp client. server is sending and reading the messages from client but the client is not able to receive the messages from server. please check it.


Answers (1)