簡介:
對Socket的封裝睁宰,使其使用較為簡單。
Server Code
// 建立一個(gè)TCP監(jiān)聽對象孝赫,來監(jiān)聽客戶端端的連接
TcpListener server = new TcpListener(IPAddress.Parse("172.26.128.1"), 8090);
// 開始監(jiān)聽客戶端的連接
server.Start();
// 接收連接上的客戶端
TcpClient client = server.AcceptTcpClient();
// 獲取客戶端的輸入輸出流對象
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int length = stream.Read(buffer, 0, buffer.Length);
Console.WriteLine("接收到客戶端的數(shù)據(jù)" + Encoding.UTF8.GetString(buffer, 0, length));
// 發(fā)送數(shù)據(jù)到客戶端
string sendMessage = "這條消息發(fā)給客戶端";
byte[] sendMessageByte = Encoding.UTF8.GetBytes(sendMessage);
stream.Write(sendMessageByte,0, sendMessageByte.Length);
// 關(guān)閉流
stream.Close();
// 關(guān)閉連接上打的客戶端
client.Close();
// 停止監(jiān)聽客戶端的連接
server.Stop();
Console.WriteLine("程序執(zhí)行完畢青柄,請按任意鍵退出");
Console.ReadKey();
Client Code
// 創(chuàng)建一個(gè)TCP 客戶端致开,綁定要連接的服務(wù)器地址和接口
TcpClient client = new TcpClient("172.26.128.1", 8090);
byte[] willSendBytes = Encoding.UTF8.GetBytes("這條消息發(fā)給服務(wù)器端");
// 發(fā)送消息給服務(wù)器
client.GetStream().Write(willSendBytes, 0, willSendBytes.Length);
byte[] buffer = new byte[1024];
// 獲取服務(wù)器端發(fā)過來的消息
int length = client.GetStream().Read(buffer, 0, 1024);
Console.WriteLine("接收到服務(wù)器發(fā)過來的消息" + Encoding.UTF8.GetString(buffer, 0, length));
// 關(guān)閉流
client.GetStream().Close();
// 釋放占用資源双戳,關(guān)閉客戶端連接
client.Close();
Console.WriteLine("程序執(zhí)行完畢拣技,請按任意鍵退出");
Console.ReadKey();