C#网络编程(同步传输字符串) - Part.2
2009-03-26 08:20:05 来源:WEB开发网然后启动多个客户端,在服务端应该可以看到下面的输出(客户端没有变化):
Server is running ...
Start Listening ...
Client Connected!127.0.0.1:8500 <-- 127.0.0.1:8196
Reading data, 52 bytes ...
Received: "Welcome To TraceFact.Net"
Client Connected!127.0.0.1:8500 <-- 127.0.0.1:8199
Reading data, 52 bytes ...
Received: "Welcome To TraceFact.Net"
由第2种情况改为第3种情况,只需要将do向下挪动几行就可以了:
// 获取一个连接,中断方法
TcpClient remoteClient = listener.AcceptTcpClient();
// 打印连接到的客户端信息
Console.WriteLine("Client Connected!{0} <-- {1}",
remoteClient.Client.LocalEndPoint, remoteClient.Client.RemoteEndPoint);
// 获得流,并写入buffer中
NetworkStream streamToClient = remoteClient.GetStream();
do {
byte[] buffer = new byte[BufferSize];
int bytesRead = streamToClient.Read(buffer, 0, BufferSize);
Console.WriteLine("Reading data, {0} bytes ...", bytesRead);
// 获得请求的字符串
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}", msg);
} while (true);
然后我们再改动一下客户端,让它发送多个请求。当我们按下S的时候,可以输入一行字符串,然后将这行字符串发送到服务端;当我们输入X的时候则退出循环:
更多精彩
赞助商链接