WPF socket通讯 UDP接收消息
客户端:
1 private Socket socket; 2 private IPEndPoint ipEndPoint; 3 private void sendMessageHandler() 4 { 5 //服务端ip,端口为192.168.1.1,8085 6 ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 8085); 7 socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); 8 try 9 { 10 socket.BeginConnect(ipEndPoint, new AsyncCallback(connectHandler), socket); 11 } 12 catch (Exception ex) 13 { 14 Console.WriteLine(ex.Message); 15 } 16 } 17 18 private void connectHandler(IAsyncResult async) 19 { 20 Socket client = async.AsyncState as Socket; 21 try 22 { 23 if (client.Connected) 24 { 25 byte[] msg = Encoding.UTF8.GetBytes("hello"); 26 try 27 { 28 System.Threading.Thread.Sleep(1000); 29 socket.Send(msg, 0, msg.Length, SocketFlags.None); 30 } 31 catch(Exception ex) 32 { 33 MessageBox.Show(ex.ToString()); 34 } 35 } 36 else 37 { 38 Console.WriteLine("没连接上"); 39 } 40 } 41 catch (Exception ex) 42 { 43 Console.WriteLine(ex.Message); 44 } 45 }
服务器端:
1 /// <summary> 2 /// 数据类 3 /// </summary> 4 public class Client 5 { 6 public Socket Socket { get; set; } 7 public byte[] _buffer; 8 /// <summary> 9 /// 为该 Socket 开辟的缓冲区 10 /// </summary> 11 public byte[] Buffer 12 { 13 get 14 { 15 if (_buffer == null) 16 _buffer = new byte[10240 * 10]; 17 return _buffer; 18 } 19 } 20 } 21 22 private Socket Server; 23 private void Begin() 24 { 25 Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 26 Server.Bind(new IPEndPoint(IPAddress.Any,8085)); 27 Server.Listen(100); 28 Server.BeginAccept(new AsyncCallback(ClientConnectComplete), null); 29 } 30 private int _receiveCount = 0;//用于统计本次接收到的字节数 31 private void ClientConnectComplete(IAsyncResult async) 32 { 33 Client client = new Client(); 34 try 35 { 36 client.Socket = Server.EndAccept(async); 37 } 38 catch (Exception) 39 { 40 Server.BeginAccept(new AsyncCallback(ClientConnectComplete), null); 41 return; 42 } 43 Console.WriteLine(client.Socket.RemoteEndPoint + " 连接成功!"); 44 45 try 46 { 47 _receiveCount = client.Socket.Receive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None); 48 } 49 catch(Exception ex) 50 { 51 MessageBox.Show(ex.ToString()); 52 } 53 //接收的消息 54 string message = Encoding.UTF8.GetString(client.Buffer, 0, _receiveCount); 55 //继续接受下一个连接 56 Server.BeginAccept(new AsyncCallback(ClientConnectComplete), null); 57 }
服务器端接收UDP字节:
1 private UdpClient udpClient; 2 private void ReceiveData() 3 { 4 udpClient = new UdpClient(int port); 5 IPEndPoint udpRemote=null; 6 while(true) 7 { 8 try 9 { 10 byte[] udpBytes=udpClient.Receive(ref udpRemote); 11 Console.Write(udpBytes.Length); 12 }catch(){} 13 } 14 }