简体   繁体   English

C#TCP客户端和服务器出现问题

[英]C# TCP Client and server having trouble

I was build client and server communication. 我正在建立客户端和服务器之间的通信。 So I am creating two separate projects. 所以我要创建两个单独的项目。 Problem is that this is not working. 问题是这不起作用。

Server code: 服务器代码:

private void Form1_Load(object sender, EventArgs e)
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;
    TcpListener server = new TcpListener(ipaddress, port);
    server.Start();
    while (true)
    {
        TcpClient client = server.AcceptTcpClient();
        label1.Text = "That Connected to Server";
    }
}

Client code: 客户代码:

private void Form1_Load(object sender, EventArgs e)
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;

    TcpClient obj = new TcpClient(ipaddress.ToString(), port);
    while (true)
    {
        label1.Text = "connected";
    }
}

This code work fine on console application. 此代码在控制台应用程序上可以正常工作。 But not working on windows form. 但不适用于Windows窗体。 I am running both application but there is no output on the screen. 我正在运行两个应用程序,但屏幕上没有输出。 Please help me how to fix it. 请帮我解决问题。

Thanks in advance 提前致谢

Windows application are event driven . Windows应用程序是事件驱动的 If you put a while(true) loop in your Form.Load event then it won't ever exit that function (and you won't ever see any interface). 如果在Form.Load事件中放入while(true)循环,则它将永远不会退出该函数(并且您将永远不会看到任何接口)。 You have to run that code in a separate thread then you'll BeginInvoke results to your UI thread. 您必须在单独的线程中运行该代码,然后开始将结果BeginInvoke到UI线程。 Something like this: 像这样:

private void Form1_Load(object sender, EventArgs e)
{
    _thread = new Thread(ListenerThread);
    _thread.IsBackground = true;
    _thread.Start();
}

private Thread _thread;

private void ListenerThread()
{
    IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
    int port = 13000;
    TcpListener server = new TcpListener(ipaddress, port);
    server.Start();
    while (true)
    {
        TcpClient client = server.AcceptTcpClient();
        BeginInvoke(new MethodInvoker(() => label1.Text = "That Connected to Server"));
    }
}

Of course on UI callback method you need to perform something more (be careful with with lambdas and anonymous delegates because of captured variables may be not thread-safe). 当然,在UI回调方法上,您需要执行更多操作(请注意使用lambda和匿名委托,因为捕获的变量可能不是线程安全的)。 Do the same for client too and you'll be done. 对客户也做同样的事情,您会完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM