TCP客户端不接收来自所有客户端的数据,但只接收一个

时间:2018-05-26 15:38:47

标签: c# tcplistener

所以我试图从每个客户端接收所有数据,但出于某种原因,它只想从一个客户端接收数据(随机),并且不想从其他客户端接收数据,所以我做错了什么?

背景工作者将每个客户注册到其自己的新背景工作者的代码:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (true)
        {
            try
            {
                client = network.AcceptTcpClient();
                streamer = client.GetStream();
                worker.ReportProgress(0,"Client Accepted");
                buffers = new byte[client.ReceiveBufferSize];
                comboBox1.Invoke(new MethodInvoker(delegate { 
comboBox1.Items.Add(client.Client.RemoteEndPoint.ToString() + "_" + 
client.Client.LocalEndPoint.ToString()); }));
                listConnectedClients.Add(client);
                BackgroundWorker theworker = new BackgroundWorker();
                theworker.DoWork += bgwhelper(client);
                theworker.RunWorkerAsync();
            } catch(Exception ex)
            {
                MessageBox.Show(ex.Message,"Client Connection Error");
                client.Close();
                streamer.Close();
                Close();
            }
        }

处理每个客户的响应数据的代码:

public DoWorkEventHandler bgwhelper(TcpClient mainclients)
    {
        try
        {
            NetworkStream mainsteams = mainclients.GetStream();
            int databases = mainsteams.Read(buffers, 0, buffers.Length);
            string data = Encoding.Unicode.GetString(buffers, 0, databases);
            if (data == "cmd1")
            {
                byte[] datacen = new byte[mainclients.ReceiveBufferSize];
                int main = mainsteams.Read(datacen, 0, datacen.Length);
                var message = Encoding.Unicode.GetString(datacen, 0, main);
                MessageBox.Show(message, 
mainclients.Client.RemoteEndPoint.ToString() + "_" + 
mainclients.Client.LocalEndPoint.ToString() + "'s Response");
            } else if (data == "cmd2")
            {

            }
        } catch(Exception)
        {
            removeclient(mainclients);
        }
        return null;
    }

0 个答案:

没有答案