接下來是客戶端:
class ClIEnt {
static void Main(string[] args) {
Console.WriteLine("ClIEnt Running ...");
TcpClient clIEnt;
ConsoleKey key;
const int BufferSize = 8192;
try {
client = new TcpClIEnt();
clIEnt.Connect("localhost", 8500); // 與服務器連接
} catch (Exception ex) {
Console.WriteLine(ex.Message);
return;
}
// 打印連接到的服務端信息
Console.WriteLine("Server Connected!{0} --> {1}",
client.Client.LocalEndPoint, client.ClIEnt.RemoteEndPoint);
NetworkStream streamToServer = clIEnt.GetStream();
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); // 獲得緩存
try {
lock(streamToServer){
streamToServer.Write(buffer, 0, buffer.Length); // 發往服務器
}
Console.WriteLine("Sent: {0}", msg);
int bytesRead;
buffer = new byte[BufferSize];
lock(streamToServer){
bytesRead = streamToServer.Read(buffer, 0, BufferSize);
}
msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received: {0}", msg);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
break;
}
}
} while (key != ConsoleKey.X);
streamToServer.Dispose();
clIEnt.Close();
Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
do {
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Q);
}
}