Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用GUI在端口上进行持续侦听?_C#_.net_Multithreading_Tcp - Fatal编程技术网

C# 如何使用GUI在端口上进行持续侦听?

C# 如何使用GUI在端口上进行持续侦听?,c#,.net,multithreading,tcp,C#,.net,Multithreading,Tcp,我正在尝试学习TCP服务器/客户端交互。我想知道如何使用GUI一直监听端口。目前我正在使用此代码: private void Form1_Load(object sender, EventArgs e) { CreateServer(); } void CreateServer() { TcpListener tcp = new TcpListener(25565); tcp.Start();

我正在尝试学习TCP服务器/客户端交互。我想知道如何使用GUI一直监听端口。目前我正在使用此代码:

    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();
    }
private void Form1\u加载(对象发送方,事件参数e)
{
CreateServer();
}
void CreateServer()
{
TcpListener tcp=新TcpListener(25565);
tcp.Start();
线程t=新线程(()=>
{
while(true)
{
var tcpClient=tcp.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(())=>
{
套接字s=tcp.AcceptSocket();
Invoke((MethodInvoker)委托{console.Text+=“Connection esatblished:”+s.RemoteEndPoint+Environment.NewLine;});
字节[]b=新字节[100];
int k=s.Receive(b);
for(int i=0;i

任何帮助都将不胜感激。

简短回答-在单独的线程/任务(TPL)中运行TCP侦听器。 对于完整的工作解决方案,您还必须使用特殊的技术将对UI的任何更改从单独的线程分派到主线程,这取决于您所使用的框架,我指的是WPF/WinForms/任何东西

下面的代码对我来说很好。阅读之前的待办事项部分

待办事项:

  • 添加到表单文本框、列表框、按钮、公开:

    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 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);
    }          
}

屏幕截图:

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();
}

创建一个线程,开始监听它&不要停止服务器

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

    Thread t = new Thread(()=>
    {
        while (true)
        {
            var tcpClient = tcp.AcceptTcpClient();
            ThreadPool.QueueUserWorkItem((_) =>
            {
                //Your server codes handling client's request.
                //Don't access UI control directly here
                //Use "Invoke" instead. 
                tcpClient.Close();
            },null);
        }
    });
    t.IsBackground = true;
    t.Start();
}

这里有一个关于mdsn的好例子:

您可以使用线程方法(如其他答案所述)或使用,在我的观点中,这是更好的方法。更好的是,您可以使用由提出的异步模型。
异步套接字将从使用中受益

嘿,我更新了密码,你能看一下吗?它似乎不起作用,可能是因为我是这个领域的新手。
它似乎不起作用
什么不起作用?你有什么错误?我看不到任何关于第三方物流的参考资料。你在用第三方物流吗?