C# UDP网络通信的实现示例

  public Form1()

  {

  InitializeComponent();

  }

  void f1()

  {

  byte[] body = new byte[1024];

  while (true)

  {

  int count = socket.Receive(body); //接受数据

  string s = Encoding.UTF8.GetString(body, 0, count);

  richTextBox1.Invoke((Action)(() =>

  {

  richTextBox1.AppendText(s + "

  ");

  richTextBox1.SelectionStart = richTextBox1.Text.Length;

  richTextBox1.ScrollToCaret();

  }));

  }

  }

  // 打开连接

  Socket socket;

  private void button1_Click(object sender, EventArgs e)

  {

  try

  {

  //1创建客户端对象

  socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

  //bind 如果前后端写的端口一致的时候 出现错误,端口号只能使用一次

  //2 绑定ip和端口号

  socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8082));

  Thread th = new Thread(f1);

  th.Start();

  }

  catch (Exception ex)

  {

  MessageBox.Show("端口号被占用");

  }

  }

  //发送消息

  private void button2_Click(object sender, EventArgs e)

  {

  if (socket != null)

  {

  //参数1 发送的字符串转成字节数组

  //参数2 发送数据的远程终端 new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8081)

  socket.SendTo(Encoding.UTF8.GetBytes("倒反天罡"), new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8081));

  }

  }

  //关闭

  private void button3_Click(object sender, EventArgs e)

  {

  socket.Close();//关闭

  socket = null;

  }