C# SocketException was unhandled

1.6k Views Asked by At

I just went through a YouTube tutorial on tcpip servers and clients and was using the code from it: https://www.youtube.com/watch?v=uXFso7xSSWk both part 1 and part 2. I have redone the code twice and have made sure that everything is the same. Whenever I run the server I get the error "SocketException was unhandled" at the line 'tcpListener.Start();' in the following method.

private void TcpServerRun()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 5004);
            tcpListener.Start();
            updateUI("Listening");
            while (true)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                updateUI("Connected");
                Thread tcpHandlerThread = new Thread (new ParameterizedThreadStart(tcpHandler));
                tcpHandlerThread.Start(client);
            }
        }

I also get the same error when I run the client, but it is at the line 'client.Connect(IPAddress.Parse("10.3.29.252"), 5004);' in the following method:

private void ConnectAsClient()
        {
            TcpClient client = new TcpClient();
            client.Connect(IPAddress.Parse("10.3.29.252"), 5004);
            NetworkStream stream = client.GetStream();
            string s = "Hello from client";
            byte[] message = Encoding.ASCII.GetBytes(s);
            stream.Write(message, 0, message.Length);
            updateUI("Message send");
            stream.Close();
            client.Close();
        }

Any and all help is much appreciated. I am pretty new to coding and very new to c# so I am sorry for anything that maybe unclear.

Here is the entire code for the server:

namespace TcpServerTutorial
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void bStartServer_Click(object sender, EventArgs e)
        {
            Thread tcpServerRunThread = new Thread(new ThreadStart(TcpServerRun));
            tcpServerRunThread.Start();
            TcpServerRun();
        }

        private void TcpServerRun()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Any, 5004);
            tcpListener.Start();
            updateUI("Listening");
            TcpClient client = tcpListener.AcceptTcpClient();
            while (true)
            {
                TcpClient client = tcpListener.AcceptTcpClient();
                updateUI("Connected");
                Thread tcpHandlerThread = new Thread (new ParameterizedThreadStart(tcpHandler));
                tcpHandlerThread.Start(client);
            }


        }

        private void tcpHandler(object client)
        {
            TcpClient mClient = (TcpClient)client;
            NetworkStream stream = mClient.GetStream();
            byte[] message = new byte[1024];
            stream.Read(message, 0, message.Length);
            updateUI("New Message = " + Encoding.ASCII.GetString(message));
            stream.Close();
            mClient.Close();
        }

        private void updateUI(string s)
        {
            Func<int> del = delegate()
            {
                textBox1.AppendText(s + System.Environment.NewLine);
                return 0;
            };
            Invoke(del);
        }
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

Bingo.Look at this chunk of code:

    private void bStartServer_Click(object sender, EventArgs e)
    {
        // Called once when the thread starts
        Thread tcpServerRunThread = new Thread(new ThreadStart(TcpServerRun));
        tcpServerRunThread.Start();
        // Called again here
        TcpServerRun();
    }

The TCPServerRun() method is being called twice: once when your thread starts, and then again via the explicit call right after you start the thread (or even possibly in reverse order). That's the call where the SocketException occurs, because the server has already started. Remove the second reference and your problem should be resolved; look for a similar situation on your client.