GUI Multi Thread TCP Server-Client - GUI crash when starting listener

39 views Asked by At

I am making a simple TCP server with GUI.

The problem I have is that when I start listening for client connections the GUI / Application stops working.

Most likely this is due to the while true that I have added. I'm not very familiar with C#, sorry if the error is obvious...

My code

private void StartListener_Click(object sender, EventArgs e)
{
    int serverPort = int.Parse(ServerPort.Text);
    string serverIP = ServerIP.Text;
    try {
        Socket ServerListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(serverIP), serverPort);
        ServerListener.Bind(endpoint);
        ServerListener.Listen(9999999);
        MessageBox.Show("The server is listening for connections", "Server is listening");
        Socket ClientSocket = default(Socket);
        int counter = 0;
        Form1 frm = new Form1();
        while (true) {
            counter++;
            ClientSocket = ServerListener.Accept();
            Thread UserThread = new Thread(new ThreadStart(() => frm.User(ClientSocket)));
            UserThread.Start();
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(string.Format("Server is not listening\n\n- IP Server or Port may be incorrect\n- Error: {0}", error.Message), "Server listener error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

public void User(Socket client)
{
    while (true)
    {
        byte[] msg = new byte[1024];
        int size = client.Receive(msg);
        client.Send(msg, 0, size, SocketFlags.None);
    }
}

Any help is more than welcome! Thank you very much for the community support!

Thanks and Best regards,

I have tried to search for support in the forum and on the Internet but unfortunately there is no help for TCP Server/Client with GUI.

0

There are 0 answers