Fork me on GitHub

C#网络编程简单实现通信小例子-1

1、主界面                                                           

2、源程序                                                          

Send

public partial class formUdpSend : Form
    {
        //声明一个UdpClient对象
        UdpClient udpClient;
        public formUdpSend()
        {
            InitializeComponent();
            //实例化UdpClient对象
            udpClient = new UdpClient();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            //获取发送信息
            string message = this.txtMessage.Text;
            //获取发送数据
            byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
            udpClient.Connect(IPAddress.Parse(this.txtIP.Text),12345);
            udpClient.Send(data, data.Length);
            this.txtMessage.Text = "";
        }
    }

Receive

 public partial class formUdpReceive : Form
    {
        UdpClient udpClient;
        Thread thread;
        public formUdpReceive()
        {
            InitializeComponent();
            //不捕获对错误线程的调用
            CheckForIllegalCrossThreadCalls = false;
            udpClient = new UdpClient(12345);
        }
        //设置监听
        public void Listen()
        {
            IPEndPoint iep = null;
            while (true)
            {
                string data = System.Text.Encoding.UTF8.GetString(udpClient.Receive(ref iep));
                this.lbReceive.Items.Add(data);
            }
        }
        private void btnReceive_Click(object sender, EventArgs e)
        {
            thread = new Thread(new ThreadStart(Listen));
            thread.IsBackground = true;
            thread.Start();
        }

        private void formUdpReceive_Load(object sender, EventArgs e)
        {

        }
    }

 

posted @ 2013-09-30 21:40  种花生的读书人  阅读(524)  评论(0编辑  收藏  举报

该博客仅作为记录笔记,转载随意