我正在尝试监听客户端多次发送数据。我不知道如何在客户端第二次发送数据时让服务器监听客户端。现在我可以多次通过客户端发送数据,但服务器只接受客户端数据一次。请帮忙。
客户端
//the client
private TcpClient client = new TcpClient();
//constructor
public ClientConnect(string Ip, int Port)
{
IP = Ip;
PORT = Port;
}
//write the data to the server
public void Connect(byte[] clientId)
{
//try to connect to the server
Thread t = new Thread(() =>
{
while (true)
{
try
{
client.Connect(new IPEndPoint(IPAddress.Parse(IP), PORT));
break;
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Trying to connect to the server...");
//pass if the connection failed
}
}
client.GetStream().Write(clientId, 0, (int)clientId.Length);
});
t.Start();
}
public void SendData(byte[] data)
{
Thread t2 = new Thread(() => {
while (true)
{
try
{
client.GetStream().Write(data, 0, (int)data.Length);
break;
}
catch (System.InvalidOperationException)
{
//pass
}
}
});
t2.Start();
}
服务器:
while (true)
{
//Listen for a potential client
TcpClient client = tcpServer.AcceptTcpClient();
Console.WriteLine(client);
Console.WriteLine("Client connection accepted from " + client.Client.RemoteEndPoint + ".");
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = client.GetStream().Read(buffer, 0, (int)buffer.Length);
byte[] buffer2 = new ArraySegment<byte>(buffer, 0, bytesRead).ToArray();
//do something with the data
}