客户端UDP发送消息至服务器端
服务器IP:192.168.1.114
服务器端口:2014
客户端
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPAddress ipaddress = IPAddress.Parse(“192.168.1.114”); XDocument doc = new XDocument(...); byte[] btContent = Encoding.GetEncoding("gb2312").GetBytes(doc.ToString()); IPEndPoint ipendpoint = new IPEndPoint(ipaddress,2014); socket.SendTo(btContent, ipendpoint); socket.Close();
服务器端
//在本机指定的端口接收 udpclient = new UdpClient(”2014“); //接收从远程主机发送过来的信息 IPEndPoint iep = new IPEndPoint(IPAddress.Any,0); while (true) { byte[] bytes = udpclient.Receive(ref iep); //客户端IP地址 string strIP = iep.Address.ToString(); string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length); XDocument doc = XDocument.Parse(strInfo); }
客户端广播,服务器端接收局域网中某端口
客户端广播的端口:2014
客户端:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //初始化一个发送广播和指定端口的网络端口实例 IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast,2014); XDocument doc = new XDocument(...); byte[] btContent = Encoding.GetEncoding("gb2312").GetBytes(doc.ToString()); //设置该scoket实例的发送形式 socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); socket.SendTo(btContent, iep); socket.Close();
服务器端:
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket协议 IPEndPoint iep = new IPEndPoint(IPAddress.Any,2014);//初始化一个侦听局域网内部所有IP和指定端口 EndPoint ep = (EndPoint)iep; socket.Bind(iep);//绑定这个实例 while (true) { byte[] bytes = new byte[1024];//设置缓冲数据流 socket.ReceiveFrom(bytes, ref ep);//接收数据,并确把数据设置到缓冲流里面 string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length); XDocument doc = XDocument.Parse(strInfo); }