

private void ListenForClients()
{
this.tcpListener.Start();
while (true) // Never ends until the Server is closed.
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
connectedClients++; // Increment the number of clients that have communicated with us.
lblNumberOfConnections.Text = connectedClients.ToString();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
connectedClients--;
lblNumberOfConnections.Text = connectedClients.ToString();
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
// Convert the Bytes received to a string and display it on the Server Screen
string msg = encoder.GetString(message, 0, bytesRead);
WriteMessage(msg);
// Now Echo the message back
Echo(msg, encoder, clientStream);
}
tcpClient.Close();
}
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes(msg); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); // Receive the TcpServer.response. // Buffer to store the response bytes. Byte[] data = new Byte[256];
//字符串存储响应ASCII码表示。
// Read the first batch of the TcpServer response bytes. Int32 bytes = clientStream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); rtbClient.AppendText(Environment.NewLine + "From Server: " + responseData);
2016-02-23
2016-05-23
2016-02-24
2016-06-01
2016-02-29
2016-06-01
2014-05-22
2014-05-20
Asp.net,core,使用SignalR推送消息过程详细介绍
2022-03-22
2022-03-16
2022-03-16
2022-03-16
.NET6新特性试用之DateOnly和TimeOnly类型
2022-03-16
2022-03-16
2022-03-16
2022-03-16
热门源码