using System;
using System.Net; //IPAddress
using System.Net.Sockets;
using System.Text;
/*
1、C#的Socket类是对操作系统底层socket API的封装。
一个Socket对象,包含了本地Ip、本地端口、远程ip、远程端口、协议相关配置等信息,这些信息构成了最基本的沟通元素。
ip和端口构成一个网络的终端,在C#中有一个类型专门用来描述两者,这个类是IEndPoint,
定义一个IEndPoint:
IPEndPoint endpoint=new IPEndPoint(ipaddress, port);
2、建立 Socket
//SocketType.Dgram : 数据报、电报 、数据包,单个。
//ProtocolType.Udp : 协议类型 UDP的协议
ReceiveSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
3、IP 地址和端口
IPAddress ipAddress = new IPAddress(new byte[] { 192,168,0,70 });
//ip + port
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress , 7788);
4、 //4: 绑定IP地址、端口等信息到socket上,用函数Bind();
udpServer.Bind(ipEndPoint);
5、 接受数据
*/
namespace UDP服务器端
{
public class studyUdp
{
static void Main(string[] args)
{
//2: 建立socket
//SocketType.Dgram : 数据报、电报 、数据包,单个。
//ProtocolType.Udp : 协议类型 UDP的协议
Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPAddress ipAddress = new IPAddress(new byte[] { 192,168,0,70 });
//3: ip + port
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress , 7788);
//4: 绑定IP地址、端口等信息到socket上,用函数Bind();
udpServer.Bind(ipEndPoint);
// UDP Server不需要调用listen和accept
//5:【接受数据】 用 长度为1024的 byte[] → data 来接受数据。
byte[] data = new byte[1024];
//: 参数 EndPoint 指定 udpServer.ReceiveFrom 接受来着哪些IP的数据
IPEndPoint iPEndPoint2 = new IPEndPoint(IPAddress.Any, 0); //IPAddress.Any 所有IP地址, 0代表 不受限制
EndPoint ep = (EndPoint)iPEndPoint2;
//把接受到的数据 放入 data里
//length :接受到的 数据 个数。 ReceiveFrom的返回值 是 接受到的数据个数
int length = udpServer.ReceiveFrom(data, ref ep); //ref 给外部变量赋值 :ep会在ReceiveFrom方法里被改变,然后赋值给外部ep ,(out 多一个返回值)
//Encoding 转换成字符串
Encoding.UTF8.GetString(data , 0 ,length);
//
Console.WriteLine("接受到数据:"+ Encoding.UTF8.GetString(data, 0, length) );
}
}
}