在我的程序打开窗体时运行TCPListener



当我单击按钮时,我的程序会启动TCPListener。在打开TCPListener之前,它会打开一个新窗口。我希望程序在TCPListener运行时在窗口中构造项目,也就是说,我需要TCPListener在"后台"运行。我想我需要使用线程,但我不确定具体如何使用。

现在基本上:

  1. 打开窗体
  2. 永远运行TCPListener
  3. 在构造任何内容之前冻结窗体窗口,因为它正在等待TCP侦听器完成。TCP侦听器中的while循环可能也是错误的。我希望它继续接受数据

这是按钮运行的方法的代码。openForm方法也与按钮的形式相同。

    private void openForm()
    {
        if (!textBox1.Text.Equals("") && !textBox2.Text.Equals("") && !textBox3.Text.Equals("") && !textBox4.Text.Equals(""))
        {
            string fornavn = textBox1.Text;
            string efternavn = textBox2.Text;
            string medarbejdernr = textBox3.Text;
            string organisation = textBox4.Text;
            Form f = new Form1(fornavn, efternavn, medarbejdernr, organisation, this);
            f.Show();
            this.Visible = false;
            Listener listen = new Listener();
        }
        else
        {
            MessageBox.Show("Du skal angive noget i alle felter", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

这是我的TCP侦听器类。

class Listener
{
    const int PORT_NO = 5000;
    const string SERVER_IP = "127.0.0.1";
    string dataReceived;
    public Listener()
    {
        //---listen at the specified IP and port no.---
        IPAddress localAdd = IPAddress.Parse(SERVER_IP);
        TcpListener listener = new TcpListener(localAdd, PORT_NO);
        listener.Start();
        while (true)
        {
            listen(listener);
        }
    }
    private void listen(TcpListener listener)
    {
        //---incoming client connected---
        TcpClient client = listener.AcceptTcpClient();
        //---get the incoming data through a network stream---
        NetworkStream nwStream = client.GetStream();
        byte[] buffer = new byte[client.ReceiveBufferSize];
        //---read incoming stream---
        int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
        //---convert the data received into a string---
        dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
        MessageBox.Show(dataReceived +" har fået et anfald mkay", "Patient har fået anfald mkay", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //---write back the text to the client---
        client.Close();
    }
}

有几种方法可以做到这一点-我喜欢使用System.Threading.Task

 private void openForm()
    {
        if (!textBox1.Text.Equals("") && !textBox2.Text.Equals("") && !textBox3.Text.Equals("") && !textBox4.Text.Equals(""))
        {
            string fornavn = textBox1.Text;
            string efternavn = textBox2.Text;
            string medarbejdernr = textBox3.Text;
            string organisation = textBox4.Text;
            Form f = new Form1(fornavn, efternavn, medarbejdernr, organisation, this);
            f.Show();
            this.Visible = false;
            Listener listen = null;
            var taskListener = Task.Factory.StartNew(() =>
                                listen = new Listener());
        }
        else
        {
            MessageBox.Show("Du skal angive noget i alle felter", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

当然,在这种情况下,一旦openForm()方法退出,侦听对象就会脱离作用域。因此,您可能希望将Listener对象的作用域更改为该方法之外。

也可以使用后台工作者

或者创建自己的线程

这是MSDN上的任务

编辑完整示例

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            using(var f = new Form2())
            {
                f.ShowDialog();
            }
        }
    }
}
    namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        public const string SERVER_IP = "192.168.5.1";
        public const int PORT_NO = 3999;
        public Form2()
        {
            InitializeComponent();
            var t = Task.Factory.StartNew(() => Listener());
        }
        private void ExecuteSecure(Action a)
        {
            if (InvokeRequired)
                BeginInvoke(a);
            else
                a();
        }
        private void Listener()
        {
            //---listen at the specified IP and port no.---
            IPAddress localAdd = IPAddress.Parse(SERVER_IP);
            TcpListener listener = new TcpListener(localAdd, PORT_NO);
            listener.Start();
            while (true)
            {
                listen(listener);
            }
        }
        private void listen(TcpListener listener)
        {
            //---incoming client connected---
            TcpClient client = listener.AcceptTcpClient();
            //---get the incoming data through a network stream---
            NetworkStream nwStream = client.GetStream();
            byte[] buffer = new byte[client.ReceiveBufferSize];
            //---read incoming stream---
            int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
            //---convert the data received into a string---
            var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            //we are listening on a different thread so we cannot show a msgbox directly.
            ExecuteSecure(() => MessageBox.Show(dataReceived + " har fået et anfald mkay", "Patient har fået anfald mkay", MessageBoxButtons.OK, MessageBoxIcon.Error));
            //---write back the text to the client---
            client.Close();
        }
    }
}  

最新更新