Resolved Socket over UDP (its not coming)

Marcos Santos

Member
Joined
Nov 11, 2021
Messages
11
Programming Experience
1-3
Hi guys,

I am trying to send my object over UDP.

Its working fine when server and client are in the same machine, but If I put the server on my VPS, and try from my PC, it does not arrive on the server.

I thought the problem was the port, but if I send any byte empty like ( byte[] data = new byte[1024];, the server captures (it means, the port is open and its getting I guess).

UDPServer:
using GrabberServer.model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GrabberServer.socket
{
    internal class UDPServer
    {

        // Server socket
        private static Socket serverSocket;

        // Data stream
        private static byte[] dataStream;


        public static void Server_Load()
        {
            try
            {
                IPAddress serverIP = IPAddress.Parse("64.xxx.37.xxx");

                // Initialise the socket
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                // Initialise the IPEndPoint for the server and listen on port 55901
                IPEndPoint server = new IPEndPoint(serverIP, 55901);

                // Associate the socket with this IP address and port
                serverSocket.Bind(server);

                // Initialise the IPEndPoint for the clients
                IPEndPoint clients = new IPEndPoint(serverIP, 0);

                // Initialise the EndPoint for the clients
                EndPoint epSender = (EndPoint)clients;

                // Start listening for incoming data
                while (true)
                {
                    Thread.Sleep(1);
                    dataStream = new byte[serverSocket.ReceiveBufferSize];
                    serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
                }
            }
            catch (Exception ex)
            {
                // lblStatus.Text = "Error";
                Console.WriteLine("Load Error: " + ex.Message, "UDP Server");
            }
        }



        private static void SendData(IAsyncResult asyncResult)
        {
            try
            {
                serverSocket.EndSend(asyncResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine("SendData Error: " + ex.Message, "UDP Server");
            }
        }

        private static void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {

                // Initialise the IPEndPoint for the clients
                IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);

                // Initialise the EndPoint for the clients
                EndPoint epSender = (EndPoint)clients;

                // Receive all data
                serverSocket.EndReceiveFrom(asyncResult, ref epSender);

                // Get packet as byte array
                BinaryFormatter formattor = new BinaryFormatter();

                MemoryStream ms = new MemoryStream(dataStream);

                Sender.userOnline = (List<Subscription>)formattor.Deserialize(ms);

                Console.WriteLine(Sender.userOnline.Count);

                for (int i = 0; i < Sender.userOnline.Count; i++)
                {
                    Console.WriteLine(Sender.userOnline[i].accountId);
                }


                serverSocket.BeginSendTo(dataStream, 0, dataStream.Length, SocketFlags.None, epSender, new AsyncCallback(SendData), epSender);


                // Listen for more connections again...
                serverSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ReceiveData Error: " + ex.Message, "UDP Server");
            }
        }
    }
}

UDPClient:
using GrabberServer.model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GrabberServer.socket
{
    internal class UDPClient
    {
        // Client socket
        private static Socket clientSocket;

        // Server End Point
        private static EndPoint epServer;

        // Data stream
        private static byte[] dataStream;

        public static void Client_Load()
        {
            try
            {

                // Initialise server IP
               

                // Initialise socket
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                IPAddress serverIP = IPAddress.Parse("64.xxx.37.xxx");

                // Initialise the IPEndPoint for the server and use port 30000
                IPEndPoint server = new IPEndPoint(serverIP, 55901);

                // Initialise the IPEndPoint for the server and use port 30000
               // IPEndPoint server = new IPEndPoint(serverIP, 55901);

                // Initialise the EndPoint for the server
                epServer = (EndPoint)server;


                while (true)
                {
                    Thread.Sleep(1000);

                    if (Sender.userOnline != null)
                    {
                        if (Sender.userOnline.Count > 0)
                        {
                         
                            // Get packet as byte array
                            MemoryStream fs = new MemoryStream();

                            BinaryFormatter formatter = new BinaryFormatter();

                            ///Confirm p = new Confirm();

                            formatter.Serialize(fs, Sender.userOnline);

                            byte[] data = fs.ToArray();

                            Console.WriteLine(data.Length);

                            // Send data to server
                            clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epServer, new AsyncCallback(SendData), null);

                            // Initialise data stream
                            dataStream = new byte[clientSocket.ReceiveBufferSize];

                            // Begin listening for broadcasts
                            clientSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
                        }
                    }
                   
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Connection Error: " + ex.Message, "UDP Client");
            }
        }

        private static void SendData(IAsyncResult ar)
        {
            try
            {
                clientSocket.EndSend(ar);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Send Data: " + ex.Message, "UDP Client");
            }
        }

        private static void ReceiveData(IAsyncResult ar)
        {
            try
            {
                // Receive all data
                clientSocket.EndReceive(ar);


                // Reset data stream
                dataStream = new byte[1024];

                // Continue listening for broadcasts
                clientSocket.BeginReceiveFrom(dataStream, 0, dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
            }
            catch (ObjectDisposedException)
            { }
            catch (Exception ex)
            {
                Console.WriteLine("Receive Data: " + ex.Message, "UDP Client");
            }
        }
    }
}
 
Moved to "Net / Sockets" since this is more of a networking issue, rather than a console application issue.
 
Add more tracing lines on your server. Trace to see if the data arrived (after line 93). If the data arrived, but the deserialization is what is failing, then what is likely is that the GrabberServer.model assembly you are using is not exactly the same between the server and the client.
 
Add more tracing lines on your server. Trace to see if the data arrived (after line 93). If the data arrived, but the deserialization is what is failing, then what is likely is that the GrabberServer.model assembly you are using is not exactly the same between the server and the client.
Actually its the same model.

The serialization works fine on localhost, the problem is when I put the server on a VPS, a byte can be send, but the object does not get there.
 
What is the exception shown by line 113 of your server? Or does the code never make it into your server's DataReceive() method?
 
Looks like you've marked this thread resolved. What what did you need to do to fix things? It may help someone else who finds this thread in the future.
 
If you were accepting a new connection every time, then you should have gotten at least the first message. Nowhere in your problem description did you say that you are able to receive the first message, but not succeeding messages. You made it sound like no messages at all were being received at all when you ran the server on a separate machine.
 
I have the same issue. All ports are open i have one setup on my local network were probably the router is the issue and another one on a Azure VM. We were able to send udp messages to the server via Hercules software on the azure setup i am testing it via a app i made that uses udp sender.

C#:
      public async Task StartAsync(CancellationToken stoppingToken)
      {
          // Create a unique local endpoint for each listener
          var localEndpoint = new IPEndPoint(IPAddress.Any, 3000);

          BackgroundWorker bw = new BackgroundWorker();
          // Start each UDP listener on a separate thread
         Task.Run(() => UdpListener(localEndpoint, stoppingToken));
      }

   async Task UdpListener(IPEndPoint localEndpoint, CancellationToken stoppingToken)
   {
       using (var udpClient = new UdpClient(localEndpoint))
       {            
           while (true)
           {
               // Receive UDP datagrams
               //thread stops here until it recieves a UDP message
               UdpReceiveResult result = await udpClient.ReceiveAsync();
            
               // Process the received data
                Task.Run( () => ProcessMessage(result)); // TODO - razmak ispred Task.Run

               Debug.WriteLine("listen started");
           }
       }
   }
 
Last edited by a moderator:
Back
Top Bottom