我有一个简单的多线程C#服务器和客户端。当只连接一个客户端时,我可以很好地与它进行交互,但是当连接两个或更多客户端时,我似乎正在使用最后一个NetworkStream
。我希望能够做的是提供一个输入命令,指定要读取和写入的流。因此,例如,第一个客户端是“客户端1”,第二个客户端是“客户端2”。我只需在命令文本框中键入“Client 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) { }
}
那么,我该怎么做呢?
答案 0 :(得分:1)
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
类字段,然后像上面一样获取当前活动的流。