简体   繁体   English

具有多个端口和多个客户端的服务器

[英]Server with multiple ports and multiple clients

I need a server that listens on multiple ports.我需要一个监听多个端口的服务器。

Multiple clients can connect to each port.多个客户端可以连接到每个端口。 After connecting, server user can select each one of clients and send a text to it, and client will respond to this text.连接后,服务器用户可以选择每个客户端并向其发送文本,客户端将响应此文本。 I used threads for this job, but when when trying to listen on multiple port I get an error that says我使用线程来完成这项工作,但是当尝试侦听多个端口时,我收到一个错误消息

"Only one usage of each socket address (protocol/network address/port) is normally permitted". “通常每个套接字地址(协议/网络地址/端口)只允许使用一次”。

How to solve this problem, and how can I access a thread after client connect to server and send text to it?如何解决此问题,以及如何在客户端连接到服务器并向其发送文本后访问线程?

My source code:我的源代码:

private void activeToolStripMenuItem_Click(object sender, EventArgs e)
{
    //for each port entered in list box,make a thread
    if (ListBox1.Items.Count != 0)
    {
        activeToolStripMenuItem.Enabled = false;
        inactiveToolStripMenuItem.Enabled = true;
        for ( i = 0; i < ListBox1.Items.Count; ++i)
        {
            serverThread = new Thread(new ThreadStart(StartServer));
            serverThread.Start();
        }
    }
    else
    {
        MessageBox.Show("You Should Add at least 1 port, to Listening Ports List.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

private void StartServer()
{
    counter = counter + 1;
    string Remote_Host_IP;
    int j = i - 1;
    port = Convert.ToInt32(ListBox1.Items[counter]);
    TcpListener listener = new TcpListener(IPAddress.Any, port);
    listener.Start();
    while (true)
    {
        mainSocket = listener.AcceptSocket();
        // you'll need some more thread stuff down here.
        if (mainSocket.Connected)
        {
            Connected_Num = Connected_Num + 1;

            Remote_Host_IP = mainSocket.RemoteEndPoint.ToString();
            this.Invoke(new MethodInvoker(() => AddConnection(Remote_Host_IP)));
        }
    }
}

Nononono:) You need to pass/signal the port number to the accept() thread at the time of its creation, not by means of some 'counter' in the space of all the threads. Nononono :) 您需要在其创建时将端口号传递/信号给 accept() 线程,而不是通过所有线程空间中的某个“计数器”。 Also, you should not read the listbox in non-GUI threads.此外,您不应在非 GUI 线程中阅读列表框。

Iterate the list and get the port number from the ListBox in the GUI thread event-handler and pass the port number, not the ListBox index, as a creation parameter to the accept threads.迭代列表并从 GUI 线程事件处理程序中的 ListBox 获取端口号,并将端口号而不是 ListBox 索引作为创建参数传递给接受线程。

Fix that first and then think about the server user interacting with the clients.首先解决这个问题,然后考虑与客户端交互的服务器用户。 You will need some sort of protocol that allows each client/user to identify itself.您将需要某种协议来允许每个客户端/用户识别自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM