C# socket编程 使用udp实现单对单的连接对话

时间:2022-03-11 00:49:43

ipLocalPoint = new IPEndPoint(IPAddress.Parse("192.168.31.122"), 5000); //定义网络类型,数据连接类型和网络协议UDP mySocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //绑定网络地址 mySocket.Bind(ipLocalPoint); //得到客户机IP IPAddress ip = IPAddress.Parse("192.168.31.127"); int port = 5000; IPEndPoint ipep = new IPEndPoint(ip, port); RemotePoint = (EndPoint)(ipep); //启动一个新的线程,执行方法this.ReceiveHandle, //以便在一个独立的进程中执行数据接收的操作 RunningFlag = true; Thread thread = new Thread(new ThreadStart(this.ReceiveHandle)); thread.Start();

  //ReceiveHandle数据接收函数

//接收数据处理线程 string msg; byte[] data = new byte[1024]; MyInvoke myI = new MyInvoke(UpdateMsgTextBox); while (RunningFlag) { if (mySocket == null || mySocket.Available < 1) { Thread.Sleep(200); continue; } //跨线程调用控件 //接收UDP数据报,引用参数RemotePoint获得源地址 int rlen = mySocket.ReceiveFrom(data, ref RemotePoint); msg = Encoding.Default.GetString(data, 0, rlen); tbMsg.BeginInvoke (myI, new object[] { RemotePoint.ToString() + " : " + msg }); }

  //发送udp数据包

string msg; msg = tbSendMsg.Text; //发送UDP数据包 byte[] data = Encoding.Default.GetBytes(msg); mySocket.SendTo(data, data.Length, SocketFlags.None, RemotePoint);

  //更新接收的消息到winform

//接收数据显示 this.tbMsg.AppendText(msg + "\n");