1

単純なマルチスレッドのC#サーバーとクライアントがあります。1つのクライアントだけが接続されている場合は問題なく対話できますが、2つ以上のクライアントが接続されている場合は、最後のクライアントを使用しているようですNetworkStream。私ができるようにしたいのは、読み取りと書き込みのストリームを指定する入力コマンドを与えることです。したがって、たとえば、最初のクライアントは「クライアント1」であり、2番目のクライアントは「クライアント2」です。コマンドテキストボックスに「Client2」と入力するだけで、2番目のクライアントのストリームが取得されます。

問題は、テキストをクライアントに割り当てる方法がわからないことです。サーバーからの関連コードは次のとおりです。

    private void ClientThread(Object client)
    {
        NetworkStream networkStream = ((TcpClient)client).GetStream();
        Dictionary<int, NetworkStream> myClients = new Dictionary<int, NetworkStream>(); // This didn't work.
        myClients.Add(counter, ((TcpClient)client).GetStream()); // Wouldn't write.
counter = counter + 1;
        streamReader = new StreamReader(networkStream);
        streamWriter = new StreamWriter(networkStream);
        strInput = new StringBuilder();          
        while (true)
        {
            try
            {
                strInput.Append(streamReader.ReadLine());
                strInput.Append("\r\n");
            }
            catch (Exception error)
            {
                break;
            }
            Application.DoEvents();
            DisplayMessage(strInput.ToString());
            strInput.Remove(0, strInput.Length);
        }
    }

    private void textBox2_KeyDown(object sender, KeyEventArgs e)
    {
        try
        {
            if (e.KeyCode == Keys.Enter)
            {                 
                //ListView.SelectedListViewItemCollection stuff = listView1.SelectedItems;
                //ip is displayed in listView1, if I could also bind the stream for the ip 
                //to it and select it, that would be cool.
                {
                    strInput.Append(textBox2.Text.ToString());
                    streamWriter.WriteLine(strInput);
                    streamWriter.Flush();
                    strInput.Remove(0, strInput.Length);
                    if (textBox2.Text == "cls") textBox1.Text = "";
                    textBox2.Text = "";
                }
            }
        }
        catch (Exception error) { }
    }

だから、どうすればこれを行うことができますか?

4

1 に答える 1

2
NetworkStream networkStream = myClients[2];
using(streamWriter = new StreamWriter(networkStream))
{
    streamWriter.WriteLine("hello client 2"); // send something to Client 2
}

networkStream = myClients[4];
using(streamWriter = new StreamWriter(networkStream))
{
    streamWriter.WriteLine("hello client 4"); // send something to Client 4
}

明らかに、すべてのクライアントストリームを辞書に保存しています。そのストリームをにロードしてStreamWriter、データを送信するだけです。辞書myClientsクラスフィールドを作成してから、上記のように現在アクティブなストリームを取得します。

于 2011-12-24T19:46:53.820 に答える