我怎么会不断的听使用GUI端口上?端口、我怎么会、GUI

2023-09-04 22:58:06 作者:我没抽风,是风在抽我

嘿,大家好我想学习TCP服务器/客户端的交互。我想知道我怎么会听一个端口都具有图形用户界面的时间。目前我使用这个code:

Hey guys I am trying to learn TCP server/client interaction. I want to know how I would listen to a port all the time with GUI. Currently I am using this code:

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateServer();
    }

    void CreateServer()
    {
        TcpListener tcp = new TcpListener(25565);
        tcp.Start();

        Thread t = new Thread(() =>
        {

            while (true)
            {
                var tcpClient = tcp.AcceptTcpClient();

                ThreadPool.QueueUserWorkItem((_) =>
                {
                    Socket s = tcp.AcceptSocket();

                    console.Invoke((MethodInvoker)delegate { console.Text += "Connection esatblished: " + s.RemoteEndPoint + Environment.NewLine; });

                    byte[] b = new byte[100];
                    int k = s.Receive(b);


                    for (int i = 0; i < k; i++)
                    {
                        console.Text += Convert.ToChar(b[i]);
                        incoming += Convert.ToChar(b[i]);
                    }

                    MessageBox.Show(incoming);

                    console.Invoke((MethodInvoker)delegate { console.Text += incoming + Environment.NewLine; });

                    list.Invoke((MethodInvoker)delegate { list.Items.Add(incoming); });

                    ASCIIEncoding asen = new ASCIIEncoding();
                    s.Send(asen.GetBytes("\n"));

                    tcpClient.Close();
                }, null);
            }
        });
        t.IsBackground = true;
        t.Start();
    }

任何帮助将是非常美联社preciateed。

Any help would be much appreciateed.

推荐答案

答案很简单 - 在不同的线程/任务(TPL)运行TCP监听器。 对于完全可行的解决方案,你也必须执行的任何更改UI形成单独的线程主线程使用特殊的技术,它是调度取决于你使用的框架,我的意思是WPF /的WinForms /什么。

Short answer - run TCP listener in the separate Thread/Task (TPL). For full working solution you also have to implement dispatching of the any changes to UI form separate thread to main thread using special technique which is depends on Framework you are using, I mean WPF/WinForms/whatever.

以下罚款,我的作品code。阅读前TODO部分。

Code below works for me fine. Read TODO section before.

TODO:

添加到形成文本框,列表框,按钮,让市民:

Add to form Textbox, ListBox, Button, make public:

public System.Windows.Forms.TextBox console;
public System.Windows.Forms.ListBox incommingMessages;
private System.Windows.Forms.Button sendSampleDataButton;

切入点:

private static Form1 form;

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    form = new Form1();
    form.Load += OnFormLoad;
    Application.Run(form);
}

private static void OnFormLoad(object sender, EventArgs e)
{
    CreateServer();
}

服务器:

private static void CreateServer()
{
    var tcp = new TcpListener(IPAddress.Any, 25565);
    tcp.Start();

    var listeningThread = new Thread(() =>
    {
        while (true)
        {
            var tcpClient = tcp.AcceptTcpClient();
            ThreadPool.QueueUserWorkItem(param =>                                                            
            {                        
                NetworkStream stream = tcpClient.GetStream();
                string incomming;                        
                byte[] bytes = new byte[1024];
                int i = stream.Read(bytes, 0, bytes.Length);                                                
                incomming = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                form.console.Invoke(
                (MethodInvoker)delegate
                    {
                        form.console.Text += String.Format(
                            "{0} Connection esatblished: {1}{2}", 
                            DateTime.Now,
                            tcpClient.Client.RemoteEndPoint,
                            Environment.NewLine);
                    });

                MessageBox.Show(String.Format("Received: {0}", incomming));
                form.incommingMessages.Invoke((MethodInvoker)(() => form.incommingMessages.Items.Add(incomming)));
                tcpClient.Close();
            }, null);
        }
    });

    listeningThread.IsBackground = true;
    listeningThread.Start();
}

客户端

private void button1_Click(object sender, EventArgs e)
{
    Connect("localhost", "hello localhost " + Guid.NewGuid());
}

static void Connect(String server, String message)
{
    try
    {               
        Int32 port = 25565;
        TcpClient client = new TcpClient(server, port);             
        Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
        NetworkStream stream = client.GetStream();

        // Send the message to the connected TcpServer. 
        stream.Write(data, 0, data.Length);                                
        stream.Close();
        client.Close();
    }
    catch (ArgumentNullException e)
    {
        Debug.WriteLine("ArgumentNullException: {0}", e);
    }
    catch (SocketException e)
    {
        Debug.WriteLine("SocketException: {0}", e);
    }          
}

截图: