C#网络编程(同步传输字符串) - Part.2
2009-03-26 08:20:05 来源:WEB开发网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);
接下来我们先运行服务端,然后再运行客户端,输入一些字符串,来进行测试,应该能够看到下面的输出结果:
// 服务端
Server is running ...
Start Listening ...
Client Connected!127.0.0.1:8500 <-- 127.0.0.1:11004
Reading data, 44 bytes ...
Received: 欢迎访问我的博客:TraceFact.Net
Reading data, 14 bytes ...
Received: 我们一起进步!
//客户端
Client Running ...
Server Connected!127.0.0.1:11004 --> 127.0.0.1:8500
Menu: S - Send, X - Exit
Input the message: 欢迎访问我的博客:TraceFact.Net
Sent: 欢迎访问我的博客:TraceFact.Net
Input the message: 我们一起进步!
Sent: 我们一起进步!
更多精彩
赞助商链接