ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C# Socket 通信

2022-03-09 18:01:07  阅读:147  来源: 互联网

标签:Console Socket C# 通信 WriteLine new byte IPAddress


Socket 通信有服务器段和客户端 

.NET 6.0 C# 10.0

服务器端代码如下:

 1 public static void Main(string[] args)
 2     {
 3         Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 4         IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
 5         IPEndPoint endPoint = new IPEndPoint(ipaddress, 11001);
 6         serverSocket.Bind(endPoint);
 7         serverSocket.Listen(1); //接收客户端的个数
 8         Console.WriteLine($"服务已启动 准备接收数据");
 9         Socket clentSocket = serverSocket.Accept();  //可以接收客户端
10         bool isContinue = true;
11 
12         while (isContinue)
13         {
14             byte[] dataBuffer = new byte[1024];
15             int count = clentSocket.Receive(dataBuffer);
16 
17             string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0, count);
18             if (msgReceive == "stop")
19                 isContinue = false;
20             Console.WriteLine($"接收到的数据 {msgReceive}");
21 
22             string megSend = msgReceive + "Yes We Du";
23             byte[] sendData = Encoding.UTF8.GetBytes(megSend);
24             clentSocket.Send(sendData);
25             Console.WriteLine($"发送数据  {sendData}");
26         }
27 
28         Console.WriteLine($"关闭服务 收到关闭信息了");
29         Console.ReadKey();
30         clentSocket.Close();
31         serverSocket.Close();
32     }

客户端代码如下:

  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("开始发送消息");
            byte[] message = Encoding.ASCII.GetBytes("Connect the Server");  //通信时实际发送的是字节数组,所以要将发送消息转换字节
            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();  //关闭连接

 

标签:Console,Socket,C#,通信,WriteLine,new,byte,IPAddress
来源: https://www.cnblogs.com/xiaconnor/p/15986363.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有