⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 formserver.cs

📁 Udp与TCP简单例子,写的不好,切午奸笑.
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using System.Net;
using System.Net.Sockets;
using System.Threading;



namespace UDPApp
{
    public partial class FormServer : Form
    {
        private UdpClient client;
        private IPEndPoint receivePoint;

        public delegate void SetTextCallback(string text);//多线程显示文本委托
        public delegate void SetInputBoxEnabled(bool b);//设定输入框是否可用委托

        public FormServer()
        {
            InitializeComponent();

            //receivePoint.


        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 显示文本,防止在线程中显示文本导致控件共享冲突
        /// </summary>
        /// <param name="text"></param>
        public void ShowDisplayText(string text)
        {
            if (this.textBox2.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(ShowDisplayText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.Text += text;
            }
        }

        /// <summary>
        /// 多线程处理文本框设定
        /// </summary>
        /// <param name="bEnabled"></param>
        public void InputReadonly(bool bEnabled)
        {
            if (this.textBox1.InvokeRequired)
            {
                SetInputBoxEnabled d = new SetInputBoxEnabled(InputReadonly);
                this.Invoke(d, new object[] { bEnabled });
            }
            else
            {
                this.textBox1.ReadOnly=bEnabled;
            }
        }
        /// <summary>
        /// 等待接收数据包线程
        /// </summary>
        public void waitForPackets()
        {
            bool bRecieveFirstPocket = false;//是否已经收到1个数据包
            this.ShowDisplayText("\r\n开始监听端口");

            while (true)
            {
                /* Receive 方法将阻止,直到数据报从远程主机到达为止。如果数据可用,
                 * 则 Receive 方法将读取入队的第一个数据报,并将数据部分作为字节数组返回。
                 * 此方法使用发送方的 IPAddress 和端口号来填充 receivePoint 参数。
                 * */
                byte[] data = client.Receive(ref receivePoint);
                ShowDisplayText("\r\n"+System.Text.Encoding.ASCII.GetString(data));//转换并显示收到的数据
                client.Send(data, data.Length, receivePoint);//将内容重新发回客户端

                if (!bRecieveFirstPocket)//第一次收到UDP包
                {
                    
                    this.ShowDisplayText("\r\nIP:" + receivePoint.Address.ToString());//显示源IP地址
                    this.ShowDisplayText("\r\nPort:"+receivePoint.Port.ToString());//显示源端口

                    this.InputReadonly(false);//设定可以接受输入
                    bRecieveFirstPocket = true;
                }

            }
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            int pid = int.Parse(this.portid.Value.ToString());
            try
            {
                client = new UdpClient(pid);//绑定到本机的端口,用于接收数据
                receivePoint = new IPEndPoint(new IPAddress(0), 0);
                //实例化一个空的IPEndPoint对象,当收到客户端的报文时,客户端的IP和端口将
                //被复制到空的IPEndPoint

                Thread readThread = new Thread(new ThreadStart(waitForPackets));
                readThread.Start();
            }
            catch(Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string str = this.textBox1.Text;
                this.textBox2.Text += "\r\nSend:" + str;

                byte[] data = System.Text.Encoding.ASCII.GetBytes(str);

                client.Send(data, data.Length, receivePoint);//将内容发回客户端
                this.textBox2.Text += "....OK";

                this.textBox1.Clear();
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(System.Environment.ExitCode);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -