0

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

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

}

}

4

2 回答 2

3

您需要使您的应用程序线程化。所以你收到的所有东西都应该由一个线程处理。

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

于 2013-06-06T13:15:36.987 回答
1

您可以像这样实现一个计时器对象,以根据提供的间隔进行检查。然后您可以使用任务工厂来防止它锁定您的 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
         });
    }
} 
于 2013-06-06T13:33:17.233 回答