S
S
Senture2018-11-22 22:17:57
C++ / C#
Senture, 2018-11-22 22:17:57

Can't accept messages from the UDP server on the client?

Good time dear!
I am making a client-server application on the udp protocol, there are 2 applications.
1st: Server, it receives messages from clients and distributes to all clients.
2nd: Client, it sends messages to the server and receives messages from the server.
I can't get messages from the server on the client.
Server code:

spoiler
class Program
    {
        static void Main(string[] args)
        {
            UDPSocket s = new UDPSocket();
            s.Server(Console.ReadLine(), Convert.ToInt32(Console.ReadLine()));
            Console.WriteLine("Сервер запущен, ожидайте...");

            Console.ReadKey();
        }
    }

class UDPSocket
    {
        private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        private const int bufSize = 8 * 1024;
        private State state = new State();
        private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
        private AsyncCallback recv = null;
        private List<Clients> clients = new List<Clients>();

        public void AddUser(Clients client)
        {
            clients.Add(client);
        }

        public class State
        {
            public byte[] buffer = new byte[bufSize];
        }

        public void Server(string address, int port)
        {
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            socket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
            Recive();
        }

        private void Recive()
        {
                socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
                {
                    bool addClient = true;
                    State so = (State)ar.AsyncState;
                    int bytes = socket.EndReceiveFrom(ar, ref epFrom);
                    socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
                    Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(so.buffer, 0, bytes));

                    for (int i = 0; i < clients.Count; i++)
                        if (clients[i].epFrom == epFrom)
                            addClient = true;

                    if (addClient) { Clients client = new Clients(epFrom, this); }

                    BroadcastMessage(epFrom, Encoding.ASCII.GetString(so.buffer, 0, bytes));
                }, state);
        }

        public void BroadcastMessage(EndPoint end, string msg)
        {
            byte[] data = Encoding.ASCII.GetBytes(msg);
            for(int i = 0; i < clients.Count; i++)
            {
                    socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, clients[i].epFrom, (ar) =>
                    {
                        State so = (State)ar.AsyncState;
                        int bytes = socket.EndSend(ar);
                    }, state);
            }
        }
    }

    class Clients
    {
        public EndPoint epFrom = null;
        UDPSocket udpSocket = null;

        public Clients(EndPoint end, UDPSocket udp)
        {
            epFrom = end;
            udpSocket = udp;
            udpSocket.AddUser(this);
        }
    }


Client code:
spoiler
class Program
    {
        static void Main(string[] args)
        {
            UDPSocket c = new UDPSocket();
            Console.WriteLine("Введите:IP для отправки сообщений\nPort для отправки сообщений");
            c.Client(Console.ReadLine(), Convert.ToInt32(Console.ReadLine()));
            c.Send("TEST 1");

            Console.ReadKey();

            c.Send("Test $2");

            Console.ReadKey();
        }
    }

class UDPSocket
    {
        private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        private const int bufSize = 8 * 1024;
        private State state = new State();
        private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
        private AsyncCallback recv = null;

        public class State
        {
            public byte[] buffer = new byte[bufSize];
        }


        public void Client(string address, int port)
        {
            socket.Connect(IPAddress.Parse(address), port);
            Recive();
        }

        public void Send(string text)
        {
            byte[] data = Encoding.ASCII.GetBytes(text);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None,  (ar) =>
            {
                State so = (State)ar.AsyncState;
                int bytes = socket.EndSend(ar);
                Console.WriteLine("SEND: {0}, {1}", bytes, text);
            }, state);
        }

        private void Recive()
        {
            socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
                {
                    State so = (State)ar.AsyncState;
                    int bytes = socket.EndReceiveFrom(ar, ref epFrom);
                    socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
                    Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(so.buffer, 0, bytes));
                }, state);
        }
    }


As I understand it, messages do not reach the client due to the fact that Bind () is not executed, but is it possible to somehow make the user install the client on his PC and be able to receive messages from the server without opening ports? I'm interested in the implementation on UDP, not on TCP. Please tell me)
PS Thank you all very much!!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question