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();
相关推荐
朱一头zcy6 分钟前
Linux系列02:网络配置、修改hosts映射文件、关闭防火墙
linux·运维·网络
斯密码赛我是美女13 分钟前
周报(欢乐赛+信息搜集ctfshow+Trae-mcp)
网络·windows
七夜zippoe40 分钟前
Python 3.12+ 新特性深度解析:类型系统与性能革命
android·网络·python·类型系统·性能革命·3.12+
zzzsde1 小时前
【Linux】进程控制(2):进程等待&&进程替换
linux·服务器·网络
CDN3601 小时前
各种网站高防服务器选型:360CDN 高防够用吗?
服务器·网络·安全
嵌入式-老费1 小时前
vivado hls的应用(带ddr读取的ip)
服务器·网络·tcp/ip
软件工程小施同学1 小时前
区块链论文速读 CCF A--CCS 2025 (2) 附pdf下载
网络·pdf·区块链
小鱼不会骑车1 小时前
TCP 核心知识精讲:是什么 · 为什么 · 怎么做
网络·网络协议·tcp/ip
Du_chong_huan1 小时前
1.6 面对攻击的网络 | 《计算机网络:自顶向下方法》精读版
网络·安全·php
cocologin2 小时前
防火墙虚拟系统实验【华为】
网络