0

I am learning how to use UDP to communicate with other applications on the same machine, so I am going through the below program to pick up the concepts, but when I run it, I get an error message, saying:

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

What am I missing or doing wrong? Could somebody also please explain to me briefly what should happen if the program runs? Thank you

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace udpClient
{
    public class Program
    {
        public static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string input, stringData;

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            string welcome = "Hello, are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ipep);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;

            data = new byte[1024];
            int recv = server.ReceiveFrom(data, ref Remote);

            Console.WriteLine("Message received from {0}:", Remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

            // In Unity3D, replace this with update or coroutine.
            while (true)
            {
                input = Console.ReadLine();

                if (input == "exit")
                    break;

                server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
                data = new byte[1024];
                recv = server.ReceiveFrom(data, ref Remote);
                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringData);
            }

            Console.WriteLine("Stopping client ..");
            server.Close();

            // Console.WriteLine("\nPress any key ...");
            // Console.ReadKey();
        }
    }
}
  • 1
    Check this: http://stackoverflow.com/questions/2370388/socketexception-address-incompatible-with-requested-protocol – Rahul Tripathi Oct 08 '15 at 12:10
  • 3
    What is the complete error message and on what line is it raised? – Alex K. Oct 08 '15 at 12:11
  • @Rahul that example is one of the _many_ causes for this exception. OP needs to inspect their InnerException. – CodeCaster Oct 08 '15 at 12:14
  • @Alex K.Sorry, I should have said on what line... `int recv = server.ReceiveFrom(data, ref Remote);` –  Oct 08 '15 at 12:15
  • The complete err msg: `SocketException was unhandled. An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll` Additional information: An existing connection was forcibly closed by the remote host –  Oct 08 '15 at 12:16
  • 2
    The server needs to start first. This is client code. Are you sure this code actually works? The code is receiving from port zero (IPAddress.Any, 0) which I don't think will work. Need to change zero to a real port number. – jdweng Oct 08 '15 at 12:57
  • @jdweng: I am not sure what the code is supposed to do. I am just trying to learn this for the first time. How do you suggest I modify it to get a very simple example running? –  Oct 08 '15 at 13:09

1 Answers1

0

Take a look at this quick fix for your code, please note this structure is for demo only, it is not for production.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace testUDP
{
class Program
{

    static volatile Boolean receivingThreadStarted = false;

    public static void DoReceiveFrom()
    {
        byte[] data = new byte[1024];
        IPEndPoint sender = new IPEndPoint(IPAddress.Any, 9050);
        EndPoint Remote = (EndPoint)sender;
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        server.Bind(sender);
        receivingThreadStarted = true;
        int recv = server.ReceiveFrom(data, ref Remote);
        Console.WriteLine("Message received from {0}:", Remote.ToString());
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    }


    static void Main(string[] args)
    {
         byte[] data = new byte[1024];
        string input;

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        ThreadStart threadDelegate = new ThreadStart(DoReceiveFrom);
        Thread newThread = new Thread(threadDelegate);
        newThread.Start();

        // Waiting to start the receiving thread.
        while (!receivingThreadStarted) Thread.Sleep(100);

        string welcome = "Hello, are you there?";
        data = Encoding.ASCII.GetBytes(welcome);
        server.SendTo(data, data.Length, SocketFlags.None, ipep);

        while (true)
        {
            input = Console.ReadLine();

            if (input == "exit")
                break;               
        }

        Console.WriteLine("Stopping client ..");
        server.Close();

    }
}

}

Hasson
  • 1,894
  • 1
  • 21
  • 25
  • **Thank you so much**... It works like a charm! I will study the code to learn it further. Will leave a comment again if I need clarification. Cheers –  Oct 08 '15 at 14:47
  • Hi Hasson, Can you elaborate on `IPAddress.Any, 9050` please? Does it mean it works on any machine (i.e. any IP address) and it is sent through the port 9050 (console port?)? Also, the part `"Message received from {0}:", remote.ToString()` which shows `127.0.0.1:65226` when I run the program -- is this a port number again? –  Oct 13 '15 at 07:39