C# 将文本写入文本框';WINFORM中的文本属性

C# 将文本写入文本框';WINFORM中的文本属性,c#,winforms,C#,Winforms,WinForms的新功能,但不是ASP.NET或C#。正在尝试创建客户端/服务器应用程序。已成功从服务器上的客户端接收数据,但在服务器程序winform上显示数据时遇到问题。代码为: 服务器应用程序代码: using System; using System.Windows.Forms; using System.Net.Sockets; using System.Net; namespace Server_App { public partial class Form1 : Form

WinForms的新功能,但不是ASP.NET或C#。正在尝试创建客户端/服务器应用程序。已成功从服务器上的客户端接收数据,但在服务器程序winform上显示数据时遇到问题。代码为:

服务器应用程序代码:

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace Server_App
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
            TcpListenerEx listener = new TcpListenerEx(ep); //set host to listen
            if (!listener.Active)
            {
                listener.Start();
            }
            while (true)
            {
                const int byteSize = 1024 * 1024;
                byte[] message = new byte[byteSize];
                var s = listener.AcceptTcpClient();
                s.GetStream().Read(message, 0, byteSize); //obtaining network stream and receiving data through .Read()
                message = cleanMessage(message);                
                string g = System.Text.Encoding.UTF8.GetString(message);
                addMessage(g);    
            }
        }

        private void addMessage(string m)
        {
                this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;
        }

        private byte[] cleanMessage(byte[] rawMessageByte)
        {
            byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
            return cleanMessage;
        }
    }
}
客户端应用程序代码:

using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientApp
{
    public partial class ClientApp : Form
    {
        public ClientApp()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text);             
            using (var client = new TcpClient("127.0.0.1", 1234))//make connection with the host
            {
                NetworkStream stream = client.GetStream();/*obtain network stream*/                
                stream.Write(message, 0, message.Length);
            }
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            txtFromClient.Text = "";
        }
    }
}

除了在服务器程序的Form1文本框中显示接收到的数据外,一切都按计划进行。调试时,我确认了行
this.textBox1.Text=textBox1.Text+Environment.NewLine+“>>”+m的变量
m
中接收到的正确值。唯一的问题是该值无法显示,因此无法在服务器程序的Form1上看到

在@AdrianoRepetti的帮助和指导下,通过以下代码提供了给定问题的解决方案:

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Linq;

namespace Server_App
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
            if(!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess.
            }
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            IPEndPoint ep = e.Argument as IPEndPoint;
            TcpListenerEx listener = new TcpListenerEx(ep);
            if (!listener.Active)
            {
                listener.Start();
            }
            while (true)
            {
                try
                {
                    const int byteSize = 1024 * 1024;
                    byte[] message = new byte[byteSize];
                    using (var s = listener.AcceptTcpClient())
                    {
                        s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read()
                        message = cleanMessage(message);
                        string g = System.Text.Encoding.UTF8.GetString(message);
                        backgroundWorker1.ReportProgress(0, g);
                    }                    
                }
                catch (Exception ex)
                {
                     backgroundWorker1.ReportProgress(0, ex.Message);
                }
                finally
                {
                    listener.Stop();
                }
            }            
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            textBox1.AppendText(Environment.NewLine + ">> " + e.UserState);
        }

        private byte[] cleanMessage(byte[] rawMessageByte)
        {
            byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
            return cleanMessage;
        }
    }
}

希望能有帮助

在@AdrianoRepetti的帮助和指导下,通过以下代码提供了给定问题的解决方案:

using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Linq;

namespace Server_App
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 1234); //configure host
            if(!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync(ep); //called to start a process on the worker thread and send argument (listener) to our workerprocess.
            }
        }

        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            IPEndPoint ep = e.Argument as IPEndPoint;
            TcpListenerEx listener = new TcpListenerEx(ep);
            if (!listener.Active)
            {
                listener.Start();
            }
            while (true)
            {
                try
                {
                    const int byteSize = 1024 * 1024;
                    byte[] message = new byte[byteSize];
                    using (var s = listener.AcceptTcpClient())
                    {
                        s.GetStream().Read(message, 0, byteSize);//obtaining network stream and receiving data through .Read()
                        message = cleanMessage(message);
                        string g = System.Text.Encoding.UTF8.GetString(message);
                        backgroundWorker1.ReportProgress(0, g);
                    }                    
                }
                catch (Exception ex)
                {
                     backgroundWorker1.ReportProgress(0, ex.Message);
                }
                finally
                {
                    listener.Stop();
                }
            }            
        }

        private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            textBox1.AppendText(Environment.NewLine + ">> " + e.UserState);
        }

        private byte[] cleanMessage(byte[] rawMessageByte)
        {
            byte[] cleanMessage = rawMessageByte.Where(b => b != 0).ToArray();
            return cleanMessage;
        }
    }
}

希望能有帮助

您的文本框支持多行吗?@AlfieGoodacre
multiline
对于服务器应用程序代码的
Form1
上的
textBox1
设置为“true”。是。单击处理程序在
while(true)
循环中接收消息。它将永远不会退出,然后控件将永远不会有机会刷新(应用程序将挂起)。将其移动到
BackgroundWorker
。另一件小事:您不需要同时调用
Dispose()
Close()
,并且可以使用
来简化它。我肯定还有其他关于同一问题的问题(要像dupe一样关闭此问题),但现在找不到,请尝试使用textBox1.AppendText(textBox1.Text+Environment.NewLine+“>”+m);要查看差异,请将(临时!!!)
Application.DoEvents()
放入循环中。应用程序将按预期开始工作。然后立即删除它并将代码从
移动,而(true)
循环进入
BackgroundWorker
,它会很好地工作。您的文本框是否支持多行?@AlfieGoodacre
多行
在服务器应用程序代码的
Form1
上为
textBox1
设置为“true”。是。单击处理程序在
while(true)
循环中接收消息。它将永远不会退出,然后控件将永远不会有机会刷新(应用程序将挂起)。将其移动到
BackgroundWorker
。另一件小事:您不需要同时调用
Dispose()
Close()
,并且可以使用
来简化它。我肯定还有其他关于同一问题的问题(要像dupe一样关闭此问题),但现在找不到,请尝试使用textBox1.AppendText(textBox1.Text+Environment.NewLine+“>”+m);要查看差异,请将(临时!!!)
Application.DoEvents()
放入循环中。应用程序将按预期开始工作。然后立即删除它,并将代码从
while(true)
循环移动到
BackgroundWorker
中,只需几件小事,它就能很好地工作:我将listener.Stop()放在finally{}块中(因为在处理表单时后台线程会被中断)。启动前检查backgroundWorker是否已在工作(backgroundWorker.IsBusy属性):)不要添加空的catch块,它将隐藏错误。只需尝试{}finally{}空的catch块现在已经有了一行代码。现在如何转换此应用程序来侦听异步请求@AdrianoRepetti从这里开始?@AdrianoRepetti你在那里的伙伴?只需几件小事:我会将listener.Stop()放在finally{}块中(因为在处理表单时后台线程将被中断)。启动前检查backgroundWorker是否已在工作(backgroundWorker.IsBusy属性):)不要添加空的catch块,它将隐藏错误。只需尝试{}最后{}空的catch块现在有了一行代码。现在如何转换此应用程序来侦听异步请求@AdrianoRepetti从这里开始?@AdrianoRepetti你在那里吗?