C#网络编程(同步传输字符串) - Part.2
2009-03-26 08:20:05 来源:WEB开发网最后我们运行程序,然后输入一串英文字符串,然后看一下输出:
// 客户端
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);
}
}
}
更多精彩
赞助商链接