最後我們運行程序,然後輸入一串英文字符串,然後看一下輸出:
// 客戶端
ClIEnt is running ...
Server Connected!127.0.0.1:12662 --> 127.0.0.1:8500
Menu: S - Send, X - Exit
Input the message: Hello, I'm jimmy zhang.
Sent: Hello, I'm jimmy zhang.
Received: HELLO, I'M JIMMY ZHANG.
// 服務端
Server is running ...
Start Listening ...
ClIEnt Connected!127.0.0.1:8500 <-- 127.0.0.1:12662
Reading data, 46 bytes ...
Received: Hello, I'm jimmy zhang.
Sent: HELLO, I'M JIMMY ZHANG.
看到這裡,我想你應該對使用TcpClIEnt和TcpListener進行C#網絡編程有了一個初步的認識,可以說 是剛剛入門了,後面的路還很長。本章的所有操作都是同步操作,像上面的代碼也只是作為一個入門的范 例,實際當中,一個服務端只能為一個客戶端提供服務的情況是不存在的,下面就讓我們來看看上面所說 的第四種情況,如何進行異步的服務端編程。
附錄:ASCII、UTF8、Uncicode編碼下的中英文字符大小
private static void ShowCode() {
string[] strArray = { "b", "abcd", "乙", "甲乙丙丁" };
byte[] buffer;
string mode, back;
foreach (string str in strArray) {
for (int i = 0; i <= 2; i++) {
if (i == 0) {
buffer = Encoding.ASCII.GetBytes(str);
back = Encoding.ASCII.GetString(buffer, 0, buffer.Length);
mode = "ASCII";
} else if (i == 1) {
buffer = Encoding.UTF8.GetBytes(str);
back = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
mode = "UTF8";
} else {
buffer = Encoding.Unicode.GetBytes(str);
back = Encoding.Unicode.GetString(buffer, 0, buffer.Length);
mode = "Unicode";
}
Console.WriteLine("Mode: {0}, String: {1}, Buffer.Length: {2}",
mode, str, buffer.Length);
Console.WriteLine("Buffer:");
for (int j = 0; j <= buffer.Length - 1; j++) {
Console.Write(buffer[j] + " ");
}
Console.WriteLine("\nRetrived: {0}\n", back);
}
}
}