UDP服务端客户端

下载

界面:

代码:form1.cs

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.Tasks;
using System.Windows.Forms;

namespace udpClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void ShowLog(string msg)
        {
            txtMsg.Text += msg + "\r\n";
        }
        UdpClient udpServ = null;
        bool bsrvRun = false;
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if(udpServ==null)
            {
                int udpPort = 0;
                if (!int.TryParse(txtSeverPort.Text, out udpPort))
                {
                    MessageBox.Show("端口必须为数字");
                    return;
                }
                udpServ = new UdpClient(udpPort, AddressFamily.InterNetwork);
                bsrvRun = true;
                ReceiveMessage();
                btnOpen.Enabled = false;
                ShowLog("UDP服务端启动监听端口"+ txtSeverPort.Text);
            }
        }

        private async void ReceiveMessage()
        {
            while (bsrvRun)
            {
                if (udpServ == null)
                    return;

                try
                {
                    UdpReceiveResult udpReceiveResult = await udpServ.ReceiveAsync();
                    string remoteip = udpReceiveResult.RemoteEndPoint.Address.ToString();

                    string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
                    ShowLog("接收到"+ remoteip + "的Udp数据:" + message);
                }
                catch (Exception ex)
                {
                    ShowLog("UDP客户端发生异常ReceiveMessage:" + ex.Message);
                }
            }
        }

        private void btnCloseSv_Click(object sender, EventArgs e)
        {
            bsrvRun = false;
            if (udpServ == null)
                return;

            try
            {
                udpServ.Client.Shutdown(SocketShutdown.Both);
                udpServ.Close();
                udpServ = null;
            }
            catch
            {
            }
            ShowLog("UDP服务端已关闭");
        }

        UdpClient udpCl = null;
        private async void btnSend_Click(object sender, EventArgs e)
        {
            if(udpCl==null)
              udpCl = new UdpClient(0, AddressFamily.InterNetwork);
            
            byte[] buffer = Encoding.UTF8.GetBytes(txtSendData.Text);
            await udpCl.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(txtRemotIP.Text), int.Parse(txtRemotPort.Text)));
            ShowLog(string.Format("向服务端{0}:{1}发送UDP包:{2}", txtRemotIP.Text, txtRemotPort.Text, txtSendData.Text));
        }
    }
}

 

posted @ 2022-09-21 15:05  小y  阅读(89)  评论(0编辑  收藏  举报