【发布时间】:2021-08-12 17:34:30
【问题描述】:
我使用分层架构。我创建了一个服务器。我希望服务器在数据到达时进行监听。 这是我在 DataAccess 层中的服务器代码。
public class ServerDal : IServerDal
{
private TcpListener server;
private TcpClient client = new TcpClient();
public bool ServerStart(NetStatus netStatus)
{
bool status = false;
try
{
server = new TcpListener(IPAddress.Parse(netStatus.IPAddress), netStatus.Port);
server.Start();
status = true;
}
catch (SocketException ex)
{
Console.WriteLine("Starting Server Error..." + ex);
status = false;
}
return status;
}
public string ReceiveAndSend(NetStatus netStatus)
{
Byte[] bytes = new Byte[1024];
String data = null;
Mutex mutex = new Mutex(false, "TcpIpReceive");
mutex.WaitOne();
if (!client.Connected)
client = server.AcceptTcpClient();
try
{
NetworkStream stream = client.GetStream();
int i;
if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: " + data);
}
}
catch (Exception ex)
{
Console.WriteLine("Connection Error..." + ex);
client.Close();
}
finally
{
mutex.ReleaseMutex();
}
return data;
}
我可以监听首先连接到服务器的客户端。当第一个连接客户端断开连接时,我可以监听第二个连接客户端。 当两个客户端都发送数据时,我想听。我怎样才能做到这一点 ?。感谢您的帮助
【问题讨论】:
-
我有一个通过
TcpClient但在Russian StackOverflow上的HTTP代码sn-p。一次支持无限的客户端。简而言之 - 使用Acynchronous Programming。TcpListener公开async方法。
标签: c# networking tcp tcpclient tcplistener