Loading... 好记性不如烂笔头 ## 1.什么是Socket ![](https://img-blog.csdnimg.cn/928ac2a3558943fa87c304632769c448.png) ## 2.Socket通信模型: ![](https://img-blog.csdnimg.cn/46a028ea92d649b0b24b0d68cecf05eb.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6L-35oGL6Ieq55WZ5Zyw,size_20,color_FFFFFF,t_70,g_se,x_16) 第一步:服务端监听某个端口 第二步:客户端向服务端地址和端口发起Socket请求 第三步:服务器接收连接请求后创建Socket连接,并维护这个连接队列 第四步:客户端和服务端就建立起了双工同信,客户端与服务端就可以实现彼此发送消息 ## 3.服务端代码的实现 ``` using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Server { class Program { static Socket ReceiveSocket; static void Main(string[] args) { int port = 8885; IPAddress ip = IPAddress.Any; // 侦听所有网络客户接口的客活动 ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 <br> ReceiveSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true); //有关套接字设置 IPEndPoint endPoint = new IPEndPoint(ip, port); ReceiveSocket.Bind(new IPEndPoint(ip, port)); //绑定IP地址和端口号 ReceiveSocket.Listen(10); //设定最多有10个排队连接请求 Console.WriteLine("建立连接"); Socket socket = ReceiveSocket.Accept(); byte[] receive = new byte[1024]; socket.Receive(receive); Console.WriteLine("接收到消息:" + Encoding.ASCII.GetString(receive)); byte[] send = Encoding.ASCII.GetBytes("Success receive the message,send the back the message"); socket.Send(send); Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(send)); Console.ReadLine(); } } } ``` ## 4.客户端代码的实现 ``` using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Client { class Program { // 1:建立一个Socket对像; //2:用socket对像的Connect()方法以上面建立的EndPoint对像做为参数,向服务器发出连接请求; //3:如果连接成功,就用socket对像的Send()方法向服务器发送信息; //4:用socket对像的Receive()方法接受服务器发来的信息 ; //5:通信结束后一定记得关闭socket; static Socket ClientSocket; static void Main(string[] args) { String IP = "127.0.0.1"; int port = 8885; IPAddress ip = IPAddress.Parse(IP); //将IP地址字符串转换成IPAddress实例 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议 IPEndPoint endPoint = new IPEndPoint(ip, port); // 用指定的ip和端口号初始化IPEndPoint实例 ClientSocket.Connect(endPoint); //与远程主机建立连接 Console.WriteLine("开始发送消息"); var a= Console.ReadLine(); byte[] message = Encoding.ASCII.GetBytes(a); //通信时实际发送的是字节数组,所以要将发送消息转换字节 ClientSocket.Send(message); Console.WriteLine("发送消息为:" + Encoding.ASCII.GetString(message)); byte[] receive = new byte[1024]; int length = ClientSocket.Receive(receive); // length 接收字节数组长度 Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive)); ClientSocket.Close(); //关闭连接 } } } ``` ![](https://img-blog.csdnimg.cn/855c0284866f4082a34d4317098a8283.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6L-35oGL6Ieq55WZ5Zyw,size_20,color_FFFFFF,t_70,g_se,x_16) ![我的公众号](https://img-blog.csdnimg.cn/20210517111144223.png) 最后修改:2021 年 09 月 21 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏