Socket通信

Socket类似插口,用于连接客户端和服务器端

客户端:

// 创建socket
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//构造IP地址
IPAddress ipaddress = new IPAddress(new byte[] {172,16,160,50});
//ip+port 终端
IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, 1122);

tcpServer.Bind(iPEndPoint); //绑定
tcpServer.Listen(100); //设置最大的连接数
Console.WriteLine("可以通信了。。。。");
Socket client = tcpServer.Accept();//开始监听,返回一个socket接口
Console.WriteLine("一个客户端连接过来了。。。。");

服务器端:

Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//构造IP地址
IPAddress ipaddress = new IPAddress(new byte[] { 172, 16, 160, 50 });
//ip+port 终端
IPEndPoint iPEndPoint = new IPEndPoint(ipaddress, 1122);

clientSocket.Connect(iPEndPoint);//连接
Console.WriteLine("连接上服务器端了");

客户端发送到服务器端:(客户端:send,服务器端:receive)

发送数据:

string message = "今天是星期一";
clientSocket.Send(Encoding.UTF8.GetBytes(message));
Console.WriteLine("我已经发送完消息了!");

 接收数据:

byte[] date = new byte[1024];
int length = client.Receive(date);

string message = Encoding.UTF8.GetString(date);
Console.WriteLine("我接收到的数据为:"+message);

关闭连接(先打开的后关闭):

client.Close();tcpServer.Close();

clientSocket.Close();

服务器端发送到客户端:(服务器端:send,客户端:receive)

TCP协议的通信:首先只能连接一个客户端,服务端使用线程连接多个客户端,否则Accept()方法会阻塞。客户端连接后设置两个线程,一个线程用于消息的发送,一个用于消息的接收。(发送和接收是可以随时进行)。客户端也是一样。

posted @ 2022-12-06 11:22  浑浑噩噩一只小迷七  阅读(198)  评论(0)    收藏  举报