然後啟動多個客戶端,在服務端應該可以看到下面的輸出(客戶端沒有變化):
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的時候則退出循環:
NetworkStream streamToServer = clIEnt.GetStream();
ConsoleKey key;
Console.WriteLine("Menu: S - Send, X - Exit");
do {
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.S) {
// 獲取輸入的字符串
Console.Write("Input the message: ");
string msg = Console.ReadLine();
byte[] buffer = Encoding.Unicode.GetBytes(msg); // 獲得緩存
streamToServer.Write(buffer, 0, buffer.Length); // 發往服務器
Console.WriteLine("Sent: {0}", msg);
}
} while (key != ConsoleKey.X);