繁体   English   中英

如何在不单击C#中的按钮的情况下直接从TCP / IP消息传递中的服务器接收文本?

[英]how to receive text directly from server in TCP/IP messaging without click a button in C#?

我已经制作了一个WPF应用程序客户端,用于通过C#中的TCP / IP消息接收文本。 但是我必须单击button2才能从服务器接收数据。 我想问一下如何使它像聊天应用程序那样无需单击button2即可直接接收文本? 我的代码如下所示:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        textBox1.Text="Client Started";
        clientSocket.Connect("10.228.183.81", 5000);
        textBox2.Text = "Client Socket Program - Server Connected ...";

    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
         NetworkStream serverStream = clientSocket.GetStream();
            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            textBox2.Text = returndata;
    }

}

}

您需要使您的应用程序成为线程。 因此,您收到的所有内容都应由线程处理。

您可以在这里查看一个很好的示例。

您可以实现一个计时器对象,以便根据提供的间隔进行检查。 然后,您可以使用Task Factory阻止它锁定UI线程,并通过委托使用接收到的数据更新TextBox(我的情况很简单,可能不是您最有可能想要实现它的方式,仅出于示例目的给出一个想法) 。

Timer myTimer = new Timer();

//On application startup start your timer like so
myTimer.Tick += new EventHandler(TimerEventProcessor);
// checks every 5 seconds, Interval accepts double in milliseconds
myTimer.Interval = 5000;
myTimer.Start();

// Then create a event handler for your timer Tick event
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {
    // stop your timer and restart it possibly once you received data and have updated gui
    // using task will keep it from Locking UI thread
    Task.Factory.StartNew(() => 
    { 
        //perform check to socket and update UI using some type of delegate like below
        this.Invoke((MethodInvoker)delegate {
              TextBox.Append(Recieved Text From Socket); // runs on UI thread
         });
    }
} 

暂无
暂无

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

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