C# Socket 通信
2022/3/9 20:15:33
本文主要是介绍C# Socket 通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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(); //关闭连接
这篇关于C# Socket 通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具