c# UDP

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket s;
        EndPoint x;
        private void button1_Click(object sender, EventArgs e)
        {
            
            //服务器
            string ip = this.textBox1.Text;
            int p = int.Parse(this.textBox2.Text);
            IPAddress ips = IPAddress.Parse(ip);
            IPEndPoint ps = new IPEndPoint(ips, p);
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);
            s.Bind(ps);

            //客户机IP
            string ip1 = this.textBox4.Text;
            int p1 = int.Parse(this.textBox3.Text);
            int px = int.Parse(this.textBox2.Text);
            IPAddress ipsx = IPAddress.Parse(ip1);
            IPEndPoint psx = new IPEndPoint(ipsx, p1);
            x = (EndPoint)psx;
            
            //使用线程处理数据接受 
            //接受UDP数据报,引用参数X获得源地址
            Thread th = new Thread(new ThreadStart(Receive));
            th.IsBackground = true;
            th.Start();

            

        }
        public delegate void myInvoke(string s);
        void Receive() 
        {
            string msg;
            byte[] data = new byte[1024];
            myInvoke my = new myInvoke(showmsg);
            while (true) 
            {
                if (s == null || s.Available < 1) 
                {
                    Thread.Sleep(200);
                    continue;
                }
                //跨线程调用控件
                //接受UDP数据包,引用参数X源地址
                int re=s.ReceiveFrom(data,ref x);
                msg=Encoding.Default.GetString(data,0,re);
                this.textBox5.BeginInvoke(my,new object[] {x.ToString()+":"+msg});
            }
        
        }

        void showmsg(string msg) 
        {
            this.textBox5.AppendText(msg + "
");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string msg;
            msg = this.textBox6.Text;
            byte[] data = Encoding.Default.GetBytes(msg);
            s.SendTo(data,data.Length,SocketFlags.None,x);
        }
    }
}

  

原文地址:https://www.cnblogs.com/mengluo/p/5652818.html