1. 服務(wù)端代碼
// 1. 新建一個Socket 服務(wù)器端 連接對象
// 參數(shù) 尋址范圍,數(shù)據(jù)類型岛都,協(xié)議格式
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] ip = { 192, 168, 199, 117 };
IPAddress address = new IPAddress(ip);
IPEndPoint point = new IPEndPoint(address, 8090);
tcpServer.Bind(point); // 2. 綁定Ip和端口號
tcpServer.Listen(100); // 3. 設(shè)置監(jiān)聽連接的最大請求數(shù)
Socket newSocket = tcpServer.Accept(); // 4. 等待客戶端的連接拐迁,會阻塞當(dāng)前線程,直到接收到客戶端的連接
string sendMessage = "Hello Welcome Connect";
newSocket.Send(Encoding.UTF8.GetBytes(sendMessage)); // 5.向客戶端發(fā)送一條消息
byte[] data = new byte[1024];
int length = newSocket.Receive(data);
Console.WriteLine("接收到客戶端的數(shù)據(jù)"+Encoding.UTF8.GetString(data, 0, length));
Console.ReadKey();
2. 客戶端代碼
//1. 建立客戶端連接對象
// 參數(shù) 尋址范圍疗绣,數(shù)據(jù)類型线召,協(xié)議格式
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 2. 建立一個連接,請求連接到服務(wù)器
clientSocket.Connect(new IPEndPoint(new IPAddress(new byte[] { 192, 168, 199, 117 }), 8090));
// 建立一個用來接受數(shù)據(jù)的容器
byte[] data = new byte[1024];
// 3. 接受服務(wù)端發(fā)送的數(shù)據(jù)
int length = clientSocket.Receive(data); // 該數(shù)組用來接受數(shù)組多矮,接受服務(wù)端傳遞的數(shù)據(jù) , 返回值缓淹,用來表示本次接收到的數(shù)據(jù)長度
// 4. 將服務(wù)器端發(fā)送過來的數(shù)據(jù)轉(zhuǎn)換成字符串
string reciveMessage = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine(reciveMessage);
string message = Console.ReadLine();
clientSocket.Send(Encoding.UTF8.GetBytes(message));
Console.ReadKey();
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者