采用UDP广播模式写简单信息传输工具~

原文:http://ms.mblogger.cn/minbear/posts/1977.aspx

 

采用UDP广播模式写简单信息传输工具~

//使用UDPClient类
//这个是我写的测试代码,供参考~
// Author : minbear
// Date : 2004-2-29


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

namespace UDPWinTest
{
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.Button btnJoin;
        private System.Windows.Forms.TextBox txtServerIP;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox txtMsgSend;
        private System.Windows.Forms.TextBox txtMessageMain;
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.Container components = null;

        private static UdpClient m_Client;

        private static int ListenerPort = 80;
        private static int SenderPort = 80;
        private static int LocalPort;
        private static int RemotePort;

        private static string m_szHostName;

        private static IPAddress m_GroupAddress;
        private static IPHostEntry m_LocalHost;
        private static IPEndPoint m_RemoteEP;
        private System.Windows.Forms.Button btnEnd;

        private static bool m_Done = false;
        private System.Windows.Forms.Button btnClose;

        private Thread t = null ;
        private Thread t2 = null ;

        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows 窗体设计器生成的代码
        /// <summary>
        /// 设计器支持所需的方法 - 不要使用代码编辑器修改
        /// 此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.btnStart = new System.Windows.Forms.Button();
            this.btnJoin = new System.Windows.Forms.Button();
            this.txtServerIP = new System.Windows.Forms.TextBox();
            this.txtMessageMain = new System.Windows.Forms.TextBox();
            this.txtMsgSend = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.btnEnd = new System.Windows.Forms.Button();
            this.btnClose = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // btnStart
            //
            this.btnStart.Location = new System.Drawing.Point(16, 16);
            this.btnStart.Name = "btnStart";
            this.btnStart.TabIndex = 0;
            this.btnStart.Text = "Start";
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            //
            // btnJoin
            //
            this.btnJoin.Location = new System.Drawing.Point(408, 16);
            this.btnJoin.Name = "btnJoin";
            this.btnJoin.TabIndex = 1;
            this.btnJoin.Text = "Join";
            this.btnJoin.Click += new System.EventHandler(this.btnJoin_Click);
            //
            // txtServerIP
            //
            this.txtServerIP.Location = new System.Drawing.Point(304, 16);
            this.txtServerIP.Name = "txtServerIP";
            this.txtServerIP.Size = new System.Drawing.Size(96, 21);
            this.txtServerIP.TabIndex = 2;
            this.txtServerIP.Text = "10.89.58.220";
            //
            // txtMessageMain
            //
            this.txtMessageMain.Location = new System.Drawing.Point(16, 48);
            this.txtMessageMain.Multiline = true;
            this.txtMessageMain.Name = "txtMessageMain";
            this.txtMessageMain.Size = new System.Drawing.Size(464, 184);
            this.txtMessageMain.TabIndex = 3;
            this.txtMessageMain.Text = "";
            //
            // txtMsgSend
            //
            this.txtMsgSend.Location = new System.Drawing.Point(16, 240);
            this.txtMsgSend.Name = "txtMsgSend";
            this.txtMsgSend.Size = new System.Drawing.Size(384, 21);
            this.txtMsgSend.TabIndex = 4;
            this.txtMsgSend.Text = "";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(408, 240);
            this.button1.Name = "button1";
            this.button1.TabIndex = 5;
            this.button1.Text = "Send";
            this.button1.Click += new System.EventHandler(this.Send_Click);
            //
            // btnEnd
            //
            this.btnEnd.Location = new System.Drawing.Point(112, 16);
            this.btnEnd.Name = "btnEnd";
            this.btnEnd.TabIndex = 6;
            this.btnEnd.Text = "End";
            this.btnEnd.Click += new System.EventHandler(this.btnEnd_Click);
            //
            // btnClose
            //
            this.btnClose.Location = new System.Drawing.Point(208, 16);
            this.btnClose.Name = "btnClose";
            this.btnClose.TabIndex = 7;
            this.btnClose.Text = "Close";
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(504, 273);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.btnEnd);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.txtMsgSend);
            this.Controls.Add(this.txtMessageMain);
            this.Controls.Add(this.txtServerIP);
            this.Controls.Add(this.btnJoin);
            this.Controls.Add(this.btnStart);
            this.Name = "Form1";
            this.Text = "UDPWinTest";
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }

        private void btnStart_Click(object sender, System.EventArgs e)
        {
            LocalPort = SenderPort;
            RemotePort = ListenerPort;

            m_szHostName = Dns.GetHostName();
            m_LocalHost = Dns.GetHostByName(m_szHostName);

            AddToMain("Local Port: " + LocalPort + ", Remote: " + RemotePort);
            AddToMain("Initializing...");

            string LocalHostIP = m_LocalHost.AddressList[0].ToString();
            string[] ArrIP = LocalHostIP.Split(new char[]{'.'});
            LocalHostIP = "224" + "." + ArrIP[1] + "." + ArrIP[2] + "." + ArrIP[3];

            Initialize(LocalHostIP);

            AddToMain("Starting Listener thread..." );
            
            //开始新线程
            t = new Thread(new ThreadStart(Listener));        //侦听线程
            t.Start();

            this.btnJoin.Enabled = false;
            this.btnStart.Enabled = false;

        }

        private void btnJoin_Click(object sender, System.EventArgs e)
        {
            LocalPort = SenderPort;
            RemotePort = ListenerPort;

            m_szHostName = Dns.GetHostName();
            m_LocalHost = Dns.GetHostByName(m_szHostName);

            AddToMain("Local Port: " + LocalPort + ", Remote: " + RemotePort);
            AddToMain("Initializing...");

            string ServerIP = this.txtServerIP.Text;
            string[] ArrIP = ServerIP.Split(new char[]{'.'});
            ServerIP = "224" + "." + ArrIP[1] + "." + ArrIP[2] + "." + ArrIP[3];

            Initialize(ServerIP);

            AddToMain("Starting Listener thread...");

            //开始新线程
            t = new Thread(new ThreadStart(Listener));        //侦听线程
            t.Start();

            this.btnStart.Enabled = false;
            this.btnJoin.Enabled = false;
        }

        private void Send_Click(object sender, System.EventArgs e)
        {
            //开始新线程
            t2 = new Thread(new ThreadStart(Send));        //侦听线程
            t2.Start();
        }

        /// <summary>
        ///
        /// </summary>
        public void Send()
        {
            Thread.Sleep(1000);

            Byte [] buffer = null;

            System.Text.Encoding ASCII = System.Text.Encoding.ASCII;

            String s = this.txtMsgSend.Text ;

            if( s.Length == 0 )
                return ;

            if(String.Compare(s,0,"@",0,1,true,CultureInfo.InvariantCulture) == 0)
            {
                m_Done = true;
                s = m_szHostName + ":@";
                Application.Exit();
            }
            else
            {
                s = m_szHostName + ":" + s;
            }


            buffer = new Byte[s.Length + 1];

            int len = ASCII.GetBytes( s.ToCharArray(), 0, s.Length, buffer, 0);

            int ecode = m_Client.Send(buffer, len, m_RemoteEP);

            if(ecode <= 0)
            {
                AddToMain("Error in send : " + ecode);
            }

            t2.Abort();

        }

        public static void Terminate()
        {
            m_Client.DropMulticastGroup(m_GroupAddress);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Initialize(string IP)
        {

            m_Client = new UdpClient(LocalPort);

            //设置广播组的网络地址
            m_GroupAddress = IPAddress.Parse(IP);

            try
            {    //加入广播组
                m_Client.JoinMulticastGroup(m_GroupAddress, 100);
            }
            catch(Exception ex)
            {
                string mm = ex.Message ;
                AddToMain("Unable to join multicast group" + ex.Message);
            }

            //设置网络端点
            m_RemoteEP = new IPEndPoint( m_GroupAddress, RemotePort );

        }

        /// <summary>
        ///
        /// </summary>
        public void Listener()
        {

            Thread.Sleep(2000);

            System.Text.Encoding ASCII = System.Text.Encoding.ASCII;

            
            while(!m_Done)
            {
                IPEndPoint endpoint = null;
                Byte[] data = m_Client.Receive(ref endpoint);

                String strData = ASCII.GetString(data);

                if( strData.IndexOf(":@") > 0 )
                {
                    Char [] separators = {':'};
                    String [] vars = strData.Split(separators);

                    if( vars[0] == m_szHostName )        //主系统已关闭
                    {
                        AddToMain("shutting down Listener thread...");
                        m_Done = true;
                    }
                    else
                    {
                        AddToMain( vars[0] + " has left the conversation");
                    }
                }
                else
                {
                    if(strData.IndexOf(":") > 0)
                    {
                        Char [] separators = {':'};
                        String [] vars = strData.Split(separators);

                        if( vars[0] != m_szHostName )
                        {
                            AddToMain(strData);
                        }
                        else
                        {
                            AddToMain(strData);
                        }
                    }
                }
            }
            t.Abort();

            AddToMain("Listener thread finished...");
            return;
        }

        private void AddToMain(string _Message)
        {
            this.txtMessageMain.Text = this.txtMessageMain.Text + _Message + "/r/n";
        }

        private void btnEnd_Click(object sender, System.EventArgs e)
        {
            this.btnStart.Enabled = true;
            this.btnJoin.Enabled = true;

            try
            {
                t.Abort();
                t.Interrupt();
                t2.Abort();
                t2.Interrupt();

                AddToMain("Closing connection...");

                m_Client.DropMulticastGroup(m_GroupAddress);
            }
            catch
            {}


            //Terminate();
        }

        private void btnClose_Click(object sender, System.EventArgs e)
        {
            try
            {
                t.Abort();
                t.Interrupt();
                t2.Abort();
                t2.Interrupt();
                Terminate() ;
            }
            catch
            {}
            Application.Exit();
        }
    }
}

深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值