C#UDP套接字侦听器服务器 - 启动&停止按钮GUI

时间:2017-10-01 06:48:01

标签: c# winforms sockets backgroundworker udpclient

我是C#和Visual Basic等新手,对任何帮助表示赞赏。

我正在制作一个简单的表格来收听UDP端口。我想使用GUI中的按钮来启动和停止UDP客户端。

到目前为止,“开始”按钮工作正常,创建UDP客户端并开始接收恒定的数据流,并将其传送到GUI中的文本框。

但是,我无法使“停止”按钮有效!

当我按下它时它会忽略它而只是继续接收,卡在一个循环中!任何想法为什么它不起作用?也许我应该使用背景工作者但我找不到任何有用的页面如何在我的代码中实现它。

非常感谢

到目前为止,这是我的代码:

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

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {

        private UdpClient Client;

        public Form1()
        {
            InitializeComponent();

            button_stop.Enabled = false;

            txtStatus.AppendText(">> Enter Port number and press Start! to begin ..." + Environment.NewLine);
            txtStatus.AppendText(">> Waiting for User to respond ..." + Environment.NewLine);

        }


        private void button_start_Click(object sender, EventArgs e)
        {

            Client = new UdpClient(Convert.ToInt32(textBox_port.Text));
            Client.BeginReceive(DataReceived, null);

            txtStatus.AppendText(">> Connecting to Server..." + Environment.NewLine);
            button_start.Enabled = false;
            button_stop.Enabled = true;

        }


        private void DataReceived(IAsyncResult ar)
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(textBox_port.Text));
            byte[] data;
            try
            {
                data = Client.EndReceive(ar, ref ip);

               if (data.Length == 0)
                   return; // No more to receive
               Client.BeginReceive(DataReceived, null);
            }
            catch (ObjectDisposedException)
            {
                return; // Connection closed
            }

            // Send the data to the UI thread
            this.BeginInvoke((Action<IPEndPoint, string>)DataReceivedUI, ip, Encoding.UTF8.GetString(data));

        }

        private void DataReceivedUI(IPEndPoint endPoint, string data)
        {
            txtLog.AppendText("[" + endPoint.ToString() + "] " + data + Environment.NewLine);
            txtStatus.AppendText(">> Receiving!" + Environment.NewLine);

        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            Client.Client.Shutdown(SocketShutdown.Receive);
            Client.Close();
            txtStatus.AppendText(">> Stopped by user..." + Environment.NewLine);
        }



        private void Form1_Load(object sender, EventArgs e)
        {


        }

    }
}

0 个答案:

没有答案