C#网络编程UDP发送与接收

本代码为C#socket网络编程程序,使用的UDP通讯协议,能够实现数据的接收与显示。
代码效果如图所示:
C#网络编程UDP发送与接收_第1张图片

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

namespace Socket编程及测试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        Socket sockRev;
        Socket sockSend;
        EndPoint revc;
        IPEndPoint send;

        Thread tdRev;

        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint add= new IPEndPoint(IPAddress.Any,Convert.ToInt16(textBox5.Text));
            sockRev = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sockRev.Bind(add);

            revc = (EndPoint)add;


            sockSend = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            send = new IPEndPoint(IPAddress.Parse(textBox3.Text), Convert.ToInt16(textBox4.Text)); 

            //建立开启接收进程
            tdRev = new Thread(DataRev);
            tdRev.IsBackground = true;
            tdRev.Start();

        }
        //数据接收函数
        public void DataRev()
        {
            int len;

            while(true)
            {
                //从目标地址接收数据
                len = sockRev.ReceiveFrom(dataRecv, ref revc);

                if (len > 0)
                {
                    //将数据进行ASCII解码,获得字符串
                    string str = Encoding.ASCII.GetString(dataRecv, 0, len);
                    //显示接收到的字符
                    textBox2.AppendText(str);
                }
            }

        }

       //定义发送缓冲区
        byte[] dataSend = new byte[1024];
        //定义接收缓冲区
        byte[] dataRecv = new byte[1024];

        private void button2_Click(object sender, EventArgs e)
        {
            //将数据转换为ASCII编码,得到byte类型的数组
            dataSend = Encoding.ASCII.GetBytes(textBox1.Text);
            //将数据发送到目标地址
            sockSend.SendTo(dataSend, dataSend.Length, SocketFlags.None, send); 
        }
    }
}

你可能感兴趣的:(C#)