Jump to content

TCP Connection Error HELP!!!

CGameDev

I am coding a server to accept multiple clients and getting a exception. Can anyone give me a hand with this please?

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace SeverClient
{
    public partial class Form1 : Form
    {

        private TcpClient client;
        public StreamReader ESMIS_STR;
        public StreamWriter ESMIS_STW;
        public string data_Send;
        public string data_receive;

        public Form1()
        {
            InitializeComponent();
            IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //Get local IP
            foreach(IPAddress address in localIP)
            {
                if(address.AddressFamily== AddressFamily.InterNetwork)
                {
                    serverIP.Text = address.ToString();
                }
            }
        }

        private async void serverBtn_Click(object sender, EventArgs e) // Start server
        {

            List<TcpListener> listener = new List<TcpListener>();
            // waiting infinity connections
            int count = 0;
            while (true)
            {
                listener.Add(new TcpListener(IPAddress.Any, int.Parse(serverPort.Text)));
                
                client = await listener[count].AcceptTcpClientAsync();
                // starting an listener to each connection
                new Task(() =>
                {
                    ESMIS_STR = new StreamReader(client.GetStream());
                    ESMIS_STW = new StreamWriter(client.GetStream());
                    ESMIS_STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync(); // Start receiving data in background
                    backgroundWorker2.WorkerSupportsCancellation = true; // Ability to cancel this thread.




                    while (client.Connected)
                    {
                        try
                        {
                        }
                        catch { }
                    }
                }).Start();
                count++;
            }


        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
        {
            while(client.Connected)
            {
                try
                {
                    data_receive = ESMIS_STR.ReadLine();
                    this.displayTB.Invoke(new MethodInvoker(delegate () { displayTB.AppendText("you : " + data_receive + "\n"); }));
                    data_receive = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //send data
        {
            if(client.Connected)
            {
                ESMIS_STW.WriteLine(data_Send);
                displayTB.Invoke(new MethodInvoker(delegate () { displayTB.AppendText("Me : " + data_Send + "\n"); }));

            }
            else
            {
                MessageBox.Show("Send Fail!");
            }
            backgroundWorker2.CancelAsync();
        }

        private void clientBtn_Click(object sender, EventArgs e) // Connect to server
        {
            client = new TcpClient();
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(clientIP.Text), int.Parse(clientPort.Text));

            try
            {
                client.Connect(IP_End);
                if (client.Connected)
                {
                    displayTB.AppendText("Connected to Server" + "\n");
                    ESMIS_STR = new StreamReader(client.GetStream());
                    ESMIS_STW = new StreamWriter(client.GetStream());
                    ESMIS_STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync(); // Start receiving data in background
                    backgroundWorker2.WorkerSupportsCancellation = true; // Ability to cancel this thread.
                }


            }catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }


        }

        private void sendBtn_Click(object sender, EventArgs e) // send button
        {
            if(sendTb.Text != "")
            {
                data_Send = sendTb.Text;
                backgroundWorker2.RunWorkerAsync();

            }
            sendTb.Text = "";



        }
    }
}

 

tcp.png

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, xiiijamaican said:

I tried to start it but it throws exception in the loop

tcp2.png

If you debug your application, I think you'll find that the error occurs on the second iteration of the loop. This is because the first time you bind to port 7777, and when you try the second time, it fails, because only one socket connection can bind to a port at the same time. Either opening a socket on a different port or not trying to open more than one will allow it to work.

 

Resources:

http://stackoverflow.com/questions/14654998/how-do-i-fix-the-error-only-one-usage-of-each-socket-address-protocol-network

˙ǝɯᴉʇ ɹnoʎ ƃuᴉʇsɐʍ ǝɹɐ noʎ 'sᴉɥʇ pɐǝɹ oʇ ƃuᴉʎɹʇ ǝɹɐ noʎ ɟI

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×