簡體   English   中英

如何讓 C# TCP 聊天服務器監聽來自多個客戶端的連接?

[英]How to have a C# TCP Chat Server listen for connections from multiple clients?

所以這是我用 c# 編寫的基於 TCP 的聊天服務器的代碼。 通過 ipv4 連接兩台計算機進行聊天沒有問題,但我希望服務器程序監聽並接受,然后向加入的計算機發送“成功加入”消息。

我想知道有沒有辦法改變這個代碼來做到這一點?

服務器代碼:

IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client

/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);

/* Start Listeneting at the specified port */
myList.Start();

MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is  :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");

Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);

ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);

byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
    Console.Write(Convert.ToChar(b[i]));
    
    /* clean up */
    s.Close();
    myList.Stop();

客戶端代碼:

TcpClient tcpclnt = new TcpClient();

tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program

MessageBox.Show("Connected");

Stream stm = tcpclnt.GetStream();

MessageBox.Show("Listening for attack information......");

byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));

謝謝你。

//幫助后的代碼

private void Connectnattk_DoWork(object sender, DoWorkEventArgs e)
        {
            {

                {
                    try
                    {
                        IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client

                        /* Initializes the Listener */
                        TcpListener myList = new TcpListener(ipAd, 8001);

                        /* Start Listeneting at the specified port */
                        myList.Start();

                        MessageBox.Show("The server is running at port 8001...");
                        MessageBox.Show("The local End point is  :" + myList.LocalEndpoint);
                        MessageBox.Show("Looking for other computer");

                        Socket s = myList.AcceptSocket();
                        Console.WriteLine("Found buddy " + s.RemoteEndPoint);

                        ASCIIEncoding asen = new ASCIIEncoding();
                        s.Send(asen.GetBytes(satt.Text));
                        MessageBox.Show("The command " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);

                        byte[] b = new byte[100];
                        int k = s.Receive(b);
                        for (int i = 0; i < k; i++)
                            Console.Write(Convert.ToChar(b[i]));

                        void ServerStart()
                        {

                            TcpListener listener = new TcpListener(IPAddress.Any, 8001);

                            listener.Start();
                            Console.WriteLine("Listening on port: 8001");

                            while (true)
                            {
                                TcpClient client = listener.AcceptTcpClient();

                                ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
                            }
                        }

                    void HandleConnection(TcpClient client)
                        {
                            Socket s = myList.AcceptSocket();
                            Console.WriteLine("Found buddy " + s.RemoteEndPoint);

                            ASCIIEncoding asen = new ASCIIEncoding();
                            s.Send(asen.GetBytes(satt.Text));

                            Console.WriteLine("Number of connected buddies: " + connectedbuddies++);

                            client.Close();
                        }


                        /* clean up */

                        s.Close();
                        myList.Stop();

                    }

在您的代碼中接受客戶端套接字是同步的,因此您只能接受一個客戶端,處理它然后循環以接受並處理另一個客戶端。

您可以使用線程為代碼添加並行性。 您創建一個處理客戶端套接字的方法並為客戶端套接字創建一個新線程。 這將允許您繼續循環以接受新的傳入客戶端套接字連接,同時處理現有的客戶端套接字連接。

static void ServerStart()
{
    TcpListener listener = new TcpListener(IPAddress.Any, 4480);

    listener.Start();
    Console.WriteLine("Listening on port: 4480");

    while (true)
    {
        // Accept the client connection before creating the thread.
        TcpClient client = listener.AcceptTcpClient();

        ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
    }
}

static void HandleConnection(TcpClient client)
{
    // Insert your code here. (Do not accept socket again here)
    client.Close();
}

我創建一個新線程來使用ThreadPool為每個TcpClient運行HandleConnection方法。 您可以在沒有 ThreadPool 的情況下創建線程,但是如果出於性能原因線程是短暫的,您將需要使用 ThreadPool 來創建它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM