Server Connection C# - System.Net.SocketException(10022)

Hemanth B 886 Reputation points
2021-08-03T07:50:12.007+00:00

Hi I want create a server connection between two computers with C#.
Here is the source code I've tried:

  Socket sks;  
        EndPoint epLocal, epRemote;  
        byte[] buffer;  
  
        private void Form2_Load(object sender, EventArgs e)  
        {  
            sks = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
  
            sks.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);  
            textLocalIp.Text = GetLocalIP();  
  
            textFriendsIp.Text = GetLocalIP();  
        }  
        private string GetLocalIP()  
  
        {  
  
            IPHostEntry host;  
  
            host = Dns.GetHostEntry(Dns.GetHostName());  
  
            foreach (IPAddress ip in host.AddressList)  
  
            {  
  
                if (ip.AddressFamily == AddressFamily.InterNetwork)  
  
                {  
  
                    return ip.ToString();  
  
                }  
  
            }  
  
            return "127.0.0.1";  
  
        }  
  
        private void button2_Click(object sender, EventArgs e)  
        {  
            try  
  
            { // binding socket  
  
                epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));  
  
                sks.Bind(epLocal);  
  
  
  
                // connect to remote IP and port  
  
                epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));  
  
                sks.Connect(epRemote);  
                buffer = new byte[1500];  
  
                sks.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new  
                AsyncCallback(MessageCallBack), buffer);  
  
  
  
                // release button to send message  
  
  
                button2.Text = "Connected";  
  
  
  
  
            }  
            catch (Exception ex)  
  
            {  
  
                MessageBox.Show(ex.ToString());  
  
            }  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            textBox5.Text = "Rock";  
            try  
  
            { // converts from string to byte[]  
  
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();  
  
                byte[] msg = new byte[1500];  
  
                msg = enc.GetBytes(textBox5.Text);  
  
  
  
                // sending the message  
  
                sks.Send(msg);  
  
  
  
                // add to listbox  
  
                listBox1.Items.Add("You:+ " + textBox5.Text);  
  
  
  
                // clear txtMessage  
  
                textBox5.Clear();  
  
            }  
  
            catch (Exception ex)  
  
            {  
  
                MessageBox.Show(ex.ToString());  
  
            }  
        }  
 private void MessageCallBack(IAsyncResult aResult)  
        {  
  
          
            try  
  
            {  
  
                int size = sks.EndReceiveFrom(aResult, ref epRemote);  
  
  
  
                // check if theres actually information if (size > 0) { // used to help us on getting the data  
  
                byte[] receivedData = new byte[1464];  
  
  
  
                // getting the message data  
  
                receivedData = (byte[])aResult.AsyncState;  
  
  
  
                // converts message data byte array to string  
  
                ASCIIEncoding eEncoding = new ASCIIEncoding();  
  
                string receivedMessage = eEncoding.GetString(receivedData);  
  
  
  
                // adding Message to the listbox  
  
                listBox1.Items.Add("Friend: " + receivedMessage);  
  
            }  
            catch (Exception exp)  
  
            {  
  
                MessageBox.Show(exp.ToString());  
  
            }  
  
  
            // starts to listen the socket again  
  
            buffer = new byte[1500];  
  
            sks.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);  
  
          
  
  
}  
    }  

But when I try this out entering my IP and port and the other device's IP and port, it throws this exception::
120114-exception.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,401 questions
{count} votes

Accepted answer
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-08-04T05:46:59.017+00:00

    Hi HemanthB-9452,
    You are binding same socket to mutiple Endpoint objects , that's why you are getting an InvalidArgument exception.
    You need to connect to remote IP and port on client side and bind socket on server side.
    Here is a code example about how to create a client application that will send message to the listener server and read it.
    Client:

    static void Main(string[] args)  
    {  
        StartClient();  
                  
    }  
    public static void StartClient()  
    {  
        byte[] bytes = new byte[1024];  
      
        try  
        {  
            // Connect to a Remote server    
            // Get Host IP Address that is used to establish a connection    
            // If a host has multiple addresses, you will get a list of addresses    
            IPHostEntry host = Dns.GetHostEntry("localhost");  
            IPAddress ipAddress = host.AddressList[0];  
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);  
      
            // Create a TCP/IP  socket.      
            Socket sender = new Socket(ipAddress.AddressFamily,  
                SocketType.Stream, ProtocolType.Tcp);  
      
            // Connect the socket to the remote endpoint. Catch any errors.      
            try  
            {  
                // Connect to Remote EndPoint    
                sender.Connect(remoteEP);  
      
                Console.WriteLine("Socket connected to {0}",  
                    sender.RemoteEndPoint.ToString());  
      
                // Encode the data string into a byte array.      
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");  
      
                // Send the data through the socket.      
                int bytesSent = sender.Send(msg);  
      
                // Receive the response from the remote device.      
                int bytesRec = sender.Receive(bytes);  
                Console.WriteLine("Echoed test = {0}",  
                    Encoding.ASCII.GetString(bytes, 0, bytesRec));  
      
                // Release the socket.      
                sender.Shutdown(SocketShutdown.Both);  
                sender.Close();  
      
            }  
            catch (ArgumentNullException ane)  
            {  
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());  
            }  
            catch (SocketException se)  
            {  
                Console.WriteLine("SocketException : {0}", se.ToString());  
            }  
            catch (Exception e)  
            {  
                Console.WriteLine("Unexpected exception : {0}", e.ToString());  
            }  
      
        }  
        catch (Exception e)  
        {  
            Console.WriteLine(e.ToString());  
        }  
    }  
    

    Server:

    static void Main(string[] args)  
    {  
      
        StartServer();  
    }  
    public static void StartServer()  
    {  
        // Get Host IP Address that is used to establish a connection    
        // If a host has multiple addresses, you will get a list of addresses    
        IPHostEntry host = Dns.GetHostEntry("localhost");  
        IPAddress ipAddress = host.AddressList[0];  
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);  
      
      
        try  
        {  
      
            // Create a Socket that will use Tcp protocol        
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);  
            // A Socket must be associated with an endpoint using the Bind method    
            listener.Bind(localEndPoint);  
            // Specify how many requests a Socket can listen before it gives Server busy response.    
            // We will listen 10 requests at a time    
            listener.Listen(10);  
      
            Console.WriteLine("Waiting for a connection...");  
            Socket handler = listener.Accept();  
      
            // Incoming data from the client.      
            string data = null;  
            byte[] bytes = null;  
      
            while (true)  
            {  
                bytes = new byte[1024];  
                int bytesRec = handler.Receive(bytes);  
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);  
                if (data.IndexOf("<EOF>") > -1)  
                {  
                    break;  
                }  
            }  
      
            Console.WriteLine("Text received : {0}", data);  
      
            byte[] msg = Encoding.ASCII.GetBytes(data);  
            handler.Send(msg);  
            handler.Shutdown(SocketShutdown.Both);  
            handler.Close();  
        }  
        catch (Exception e)  
        {  
            Console.WriteLine(e.ToString());  
        }  
      
        Console.WriteLine("\n Press any key to continue...");  
        Console.ReadKey();  
    }  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful