Socket UDP Send and Receive C#

Asked

Viewed 2,222 times

1

I’m developing a c# application that uses UDP, the problem is that I can’t answer the customer. I get the following error: Additional information: A request for sending or receiving data was not allowed because the socket is not connected and (while sending on a datagram socket using a sendto call) an address was not provided.

It follows the system: Server:

string data = "";
            byte[] d = new byte[1024];

            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 6969);


            Console.WriteLine(" S E R V E R   IS   S T A R T E D ");
            Console.WriteLine("* Waiting for Client...");
            server.Bind(remoteIPEndPoint);
            while (data != "q") {
                //data = Console.ReadLine();

                server.Receive(d);
                data = Encoding.ASCII.GetString(d);
                Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
                Console.WriteLine("Message Received " + data.TrimEnd());

                d = Encoding.ASCII.GetBytes("oi");
                server.Send(d);
                Console.WriteLine("Message sended to" + remoteIPEndPoint + " " + data);

            }

            Console.WriteLine("Press Enter Program Finished");
            Console.ReadLine(); //delay end of program
            server.Close();  //close the connection

Client

string data = "";
        byte[] d = new byte[1024];

        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


        IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6969);


        Console.WriteLine(" C L I E N T   IS   S T A R T E D ");

        server.Connect(remoteIPEndPoint);

        Console.WriteLine("* Server connected...");

        while (data != "q") {
            d = Encoding.ASCII.GetBytes("teste");
            server.Send(d);
            Console.WriteLine("Message sended to" + remoteIPEndPoint + " " + data);



            server.Receive(d); 
            data = Encoding.ASCII.GetString(d);
            Console.WriteLine("Received from server: "+data);


        }

        Console.WriteLine("Press Enter Program Finished");
        Console.ReadLine(); //delay end of program
        server.Close();  //close the connection

2 answers

2


UDP is a protocol that requires no connection, unlike TCP. What you need is an endpoint that will receive the package.

Your client code may contain something similar to the section below:

//Prepara um socket para ser utilizado como emissor
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);

//Prepara o endereço-alvo
IPEndPoint endPointServidor = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6969);

//Transforma o conteúdo a ser enviado em um array de bytes
byte[] d = Encoding.ASCII.GetBytes("teste");

//Envia o conteúdo [d] para o servidor [endPointServidor]
server.SendTo(d, endPointServidor);

Your server then may contain code similar to this:

//Prepara um socket para ser utilizado como receptor
Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

//Prepara o cliente Udp, ouvindo na porta 6969
UdpClient listener = new UdpClient(6969);

//Inicia a captura de pacotes. O metodo gerenciaRetorno sera chamado
//  sempre que um conteúdo via UDP chegar ao servidor
receiver.BeginReceive(gerenciaRetorno, listener);

    private static void gerenciaRetorno(IAsyncResult li)
    {
        IPEndPoint recEP = new IPEndPoint(IPAddress.Any, 0);
        Byte[] buffer = ((UdpClient)li.AsyncState).EndReceive(li, ref recEP);

        //[mensagem] conterá o conteúdo recebido.
        string mensagem = ASCIIEncoding.ASCII.GetString(buffer);

        //re-arma o socket para recepção
        receiver.BeginReceive(gerenciaRetorno, li.AsyncState);
    }

Source: C# UDP Socket client and server, ONLY ORIGINAL.

  • Opa Ono, if it is not asking too much, you could edit this commented reply that each function does and what are the parameters. I’m a beginner in C# and Client+Server programming (other than web JS+PHP)

  • @Kaduamaral - no problem, here is the version with comments and some corrections.

  • Ono, I have a problem with the method BeginReceive, VS points out that it does not have 2 parameters Overload, the first ones are usually bytes[] buffer or IList<ArraySegment<byte>>. I put this method in the constructor of a class I called a server, so this function gerenciaRetorno can be a method, or must be inside the constructor as well?

0

I had this problem recently. I solved the problem by putting a 500 millisecond "Sleep" before sending the bytes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.