zoukankan      html  css  js  c++  java
  • 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;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace UDP03
    {
        public partial class Form1 : Form
        {
            private Thread udpListenThread;//UDP监听线程
            private UdpClient udpserver;//UDP服务器
            private IPEndPoint remoteIpAndPort;//远程IP地址和端口
            private delegate void displayMessageDelegate();//委托
            /// <summary>
            /// 初始化UDP通讯
            /// </summary>
            public Form1()
            {
                InitializeComponent();
                udpListenThread = new Thread(new ThreadStart(udpListen));//创建监听线程
                udpListenThread.IsBackground = true;//设为后台线程
                udpListenThread.Start();//启动监听线程
                //↓ 显示本机内网IPv4地址 win7系统
                //this.textBoxHostIp.Text = Dns.GetHostEntry(Dns.GetHostName()).AddressList[3].ToString();
    
                for (int i = 0; i < Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length; i++)
                {
                    //MessageBox.Show(Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString());
                    //↓ 获取本机的IPv4地址,不知道怎么获取,只找到了这个办法
                    if (Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].AddressFamily.ToString().Equals("InterNetwork"))
                    {
                        this.textBoxHostIp.Text = Dns.GetHostEntry(Dns.GetHostName()).AddressList[i].ToString();
                        break;
                    }
                }
            }
            /// <summary>
            /// 监听线程
            /// </summary>
            private void udpListen()//监听,线程的实际代码
            {
                int i = 1;
                while (true)//循环,端口不可用自动加1
                {
                    try
                    {
                        udpserver = new UdpClient(int.Parse(this.textBoxPortNumber.Text));//创建UDP服务器,绑定要监听的端口
                        break;
                    }
                    catch
                    {
                        //就是将预设的端口号加1
                        this.textBoxPortNumber.Text = (int.Parse(this.textBoxPortNumber.Text) + i++).ToString();
                    }
                }
    
                remoteIpAndPort = new IPEndPoint(IPAddress.Any, 0);//定义IPENDPOINT,装载远程IP地址和端口                    
                string receivedStr;//保存接收的数据字符的临时变量
    
                while (true)
                {
                    try
                    {
                        //将udpserver接受到指定的远程主机的数据包转换成字符串保存在临时变量
                        receivedStr =
                            System.Text.Encoding.Default.GetString(udpserver.Receive(ref remoteIpAndPort));
    
                        //定义委托
                        displayMessageDelegate dis = delegate()
                        {
                            //string s = "
    [I received some data]";
                            //byte[] b = System.Text.Encoding.UTF8.GetBytes(s);
                            //this.udpserver.Send(b, b.Length, remoteIpAndPort);//接收到数据后返回 “[I received some data]”
                            this.textBoxRemoteIp.Text = remoteIpAndPort.Address.ToString();//远程主机的IP显示到窗体
                            this.textBoxRemotePort.Text = remoteIpAndPort.Port.ToString();//远程主机的端口号显示到窗体
                            this.txtShowData.AppendText(string.Format("
    {0}", remoteIpAndPort));//显示远程回话(当昵称用)
                            this.txtShowData.AppendText("
    " + receivedStr);//数据报显示到接收区域                        
                            this.txtShowData.ScrollToCaret();//滚动到最下面,显示最新消息
                            //↓ 更新显示本地端口号(无实际意义)
                            this.textBoxPortNumber.Text = ((IPEndPoint)(this.udpserver.Client.LocalEndPoint)).Port.ToString();
                        };
    
                        this.Invoke(dis);//执行委托
                    }
                    catch
                    {
                        break;
                    }
                }
            }
            /// <summary>
            /// 修改本地端口号 —— 修改本地监听端口号则重启线程
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void buttonUpdatePortNumber_Click(object sender, EventArgs e)
            {
                udpserver.Close();//释放UDP连接
                udpListenThread.Abort();//kill线程
                //重建线程
                udpListenThread = new Thread(new ThreadStart(udpListen));
                udpListenThread.IsBackground = true;
                udpListenThread.Start();
            }
            /// <summary>
            /// 对方IP、端口TextBox状态修改
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void checkBoxAppointIp_CheckedChanged(object sender, EventArgs e)
            {
                if (this.checkBoxAppointIp.Checked)
                {
                    this.textBoxRemoteIp.ReadOnly = false;
                    this.textBoxRemotePort.ReadOnly = false;
                }
                else
                {
                    this.textBoxRemoteIp.ReadOnly = true;
                    this.textBoxRemotePort.ReadOnly = true;
                }
            }
            /// <summary>
            /// 点击发送
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void buttonSend_Click(object sender, EventArgs e)
            {
                this.txtSendData.Focus();
                if (this.txtSendData.Text.Length == 1)
                {
                    this.txtSendData.Clear();
                    return;
                }
                try
                {
                    //将发送框中的文本转化成byte数组
                    //byte[] b = System.Text.Encoding.UTF8.GetBytes(this.richTextBoxSend.Text);
                    byte[] b = System.Text.Encoding.Default.GetBytes(this.txtSendData.Text);
                    if (this.checkBoxAppointIp.Checked)
                    {
                        remoteIpAndPort.Address = IPAddress.Parse(this.textBoxRemoteIp.Text);
                        remoteIpAndPort.Port = int.Parse(this.textBoxRemotePort.Text);
                    }
                    this.udpserver.Send(b, b.Length, remoteIpAndPort);
                    this.txtShowData.AppendText("
    " + this.textBoxHostIp.Text + ":" + this.textBoxPortNumber.Text);
                    this.txtShowData.AppendText("
    " + this.txtSendData.Text);
                    this.txtSendData.Clear();
                    this.txtShowData.ScrollToCaret();
                }
                catch
                {
                    ;
                }
            }
        }
    }
    UDP通讯小程序代码
  • 相关阅读:
    Git配置SSH访问GitHub
    vue 관련
    node
    关于CheckBox和EditText在ListView里多布局的处理
    百度地图定位
    java常用简单正则表达式写法
    Android二维码开源项目zxing编译
    Andrew XUtils的session获得和cookieStore使用
    常用易忘知识点
    替换Fragment 报错 The specified child already has a parent. You must call removeView()
  • 原文地址:https://www.cnblogs.com/lotuses/p/11361807.html
Copyright © 2011-2022 走看看