C# udp简易版
作者:互联网
直接上代码:
客户端:
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace udpClient { //udp客户端 class Program { static void Main(string[] args) { Console.WriteLine("请输入要发送的内容:"); UdpClient udpClient = new UdpClient(); while (true) { string message = Console.ReadLine(); //我的电脑是这个ip,你们自己测的时候根据实际情况而定 udpClient.SendMessage(message, "192.168.1.104", 3333); } } }
public class UdpClient { Socket udpSocket; public UdpClient() { //创建Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化 } /// <summary> /// 发送消息 /// </summary> /// <param name="messages">消息内容</param> /// <param name="strIp">目标ip</param> /// <param name="port">目标端口号</param> public int SendMessage(string message, string strIp, int port) { //发送数据 EndPoint serverPoint = new IPEndPoint(IPAddress.Parse(strIp), port); if (udpSocket == null) { Console.WriteLine("socket未初始化!"); return 0; } else if (serverPoint == null) { Console.WriteLine("目标ip和端口号不能为空!"); return 0; } else if (message == null || string.IsNullOrEmpty(message)) { Console.WriteLine("发送信息不能为空!"); return 0; } byte[] data = Encoding.UTF8.GetBytes(message); udpSocket.SendTo(data, serverPoint);//发送 return 1; } } }
服务端:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace udpServer { //udp服务器 class Program { static void Main(string[] args) { UdpServer udpServer = new UdpServer("192.168.1.104", 3333); udpServer.StartReceive(); Console.ReadLine(); } }
public class UdpServer { private Socket udpServer; public UdpServer(string strIp, int port) { //创建socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //绑定ip和端口号 try { //绑定的ip可能是错误的,要抛出异常 udpServer.Bind(new IPEndPoint(IPAddress.Parse(strIp), port)); } catch (Exception ex) { Console.WriteLine("错误信息:" + ex.Message); throw ex; } } /// <summary> /// 开始接收消息 /// </summary> public int StartReceive() { if (udpServer.LocalEndPoint == null) { Console.WriteLine("未绑定自身ip和端口号"); return 0; } new Thread(ReceiveMessage) { IsBackground = true }.Start(); return 1; } private void ReceiveMessage() { while (true) { //接收数据 EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);//j远端ip和端口,这里设定成所有的ip和端口 byte[] data = new byte[1024]; int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//程序运行到这里是会停顿的 string message = Encoding.UTF8.GetString(data, 0, length);//从索引0开始接收 Console.WriteLine("发送方ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + "-------发送方端口:" + (remoteEndPoint as IPEndPoint).Port + "-------消息内容:" + message); } } } }
结果:
标签:udp,Console,udpServer,C#,ip,System,简易版,new,using 来源: https://www.cnblogs.com/Transmuter/p/13379027.html