【发布时间】:2014-08-28 05:18:41
【问题描述】:
我有可以同时接受多个客户端的异步 tcp 服务器。客户端从服务器请求数据的场景得到了很好的服务。现在我正在尝试实现服务器必须找到特定客户端并向其发送一些数据的情况,即客户端已连接但尚未请求数据但服务器想要向其发送一些数据。如何找到已经在服务器和客户端之间运行的线程并在上面放置数据?
这是服务器代码:
public async void RunServerAsync()
{
tcpListener.Start();
while (true)
{
try
{
var client = await tcpListener.AcceptTcpClientAsync();
Accept(client);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
private async void Accept(TcpClient client)
{
//get client information
String clientEndPoint = client.Client.RemoteEndPoint.ToString();
Console.WriteLine("Client connected at " + clientEndPoint );
await Task.Yield ();
try
{
using (client)
using (NetworkStream stream = client.GetStream())
{
byte[] dataReceived = new byte[100];
while (true) //read input stream
{
try
{
int x = await stream.ReadAsync(dataReceived, 0, dataReceived.Length);
if (x != 0)
{
//pass on data for processing
byte[] dataToSend = await ProcessData(dataReceived);
//send response,if any, to the client
if (dataToSend != null)
{
await stream.WriteAsync(dataToSend, 0, dataToSend.Length);
ConsoleMessages.DisplayDataSent(dataReceived, dataToSend);
}
}
}
catch (ObjectDisposedException)
{
stream.Close();
}
}
}
} //end try
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}//end Accept(TcpClient client)
【问题讨论】:
-
我不认为这种方法我的意思是tcp客户端工作正常,我建议你使用异步方法,使用这种方法你可以处理一个线程的每个连接,使用这种方法你可以发送你的ip将您的客户端作为 id 发送到服务器,并根据需要向其发送信息
标签: c# async-await tcpclient tcplistener