c#网络Tcp和udp

TCP 通信


TCP 服务端

csharp 复制代码
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
tcpServer.Bind(ipEndPoint); // 绑定IP和端口号
tcpServer.Listen(100); // 设置最多有100人连接
Console.WriteLine("开始接客了...");
Socket client = tcpServer.Accept();
Console.WriteLine("一个客户端连接过来了!");

// 接收消息
byte[] data = new byte[1024];
int length = client.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("接收到了客户端的消息:" + msg);

// 发送消息
client.Send(Encoding.UTF8.GetBytes("来了,随便坐"));

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

TCP 客户端

csharp 复制代码
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
tcpClient.Connect(ipEndPoint);
Console.WriteLine("连接上服务器端了!");

// 发送消息
string msg = "我上线了";
tcpClient.Send(Encoding.UTF8.GetBytes(msg));

// 接收消息
byte[] data = new byte[1024];
int length = tcpClient.Receive(data);
Console.WriteLine("收到服务器端的消息:" + Encoding.UTF8.GetString(data, 0, length));

tcpClient.Close();

TCP 和 UDP 的区别


  • 基于连接(TCP)和无连接(UDP)
  • 对系统资源的要求(TCP 较多,UDP 少)
  • UDP 程序结构较简单
  • 流模式(TCP)与 数据报模式(UDP)
  • TCP 保证数据的正确性,UDP 可能丢包
  • TCP 保证数据顺序,UDP 不保证

UDP 通信


UDP 服务端

csharp 复制代码
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
udpServer.Bind(ipEndPoint);

IPEndPoint ipEndPoint2 = new IPEndPoint(IPAddress.Any, 0);
EndPoint ep = (EndPoint)ipEndPoint2;
byte[] data = new byte[1024];
int length = udpServer.ReceiveFrom(data, ref ep); // 接收数据
Console.WriteLine("接收到数据:" + Encoding.UTF8.GetString(data, 0, length));

udpServer.Close();

UDP 客户端

csharp 复制代码
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 5 });
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 7788);
byte[] data = Encoding.UTF8.GetBytes("您好,客户端上线了!");
udpClient.SendTo(data, ipEndPoint); // 发送数据

udpClient.Close();
相关推荐
烛阴1 小时前
C# 正则表达式(2):Regex 基础语法与常用 API 全解析
前端·正则表达式·c#
Poetinthedusk2 小时前
C#实现图片统一位深
开发语言·c#
掘根3 小时前
【消息队列项目】虚拟机管理实现
网络
bugcome_com3 小时前
深入理解 C# 中的装箱与拆箱
c#
切糕师学AI3 小时前
使用 VS Code 开发 C# 程序时,如何配置 launch.json
vscode·c#·visual studio code
老王熬夜敲代码4 小时前
网络中数据传输的具体过程
linux·网络·笔记
汤愈韬5 小时前
TK_网络基础和常见攻击(笔记)
网络·笔记
bugcome_com5 小时前
深入理解 C# 中 new 关键字的三重核心语义
c#·.net
北邮刘老师6 小时前
【智能体互联协议解析】需要“智能体名字系统”(ANS)吗?
网络·人工智能·大模型·智能体·智能体互联网
照海19Gin7 小时前
【企业网架构实验解析】三层组网与 AC+AP 无线部署的协议逻辑(eNSP 仿真实践)
网络