对WinForms不适用,但不适用于ASP.NET或C#。试图制作客户端/服务器应用程序。成功地从服务器上的客户端接收数据,但在服务器程序winform上显示它有麻烦。代码如下:在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;
}
}
}
客户端应用代码:按计划,除了对服务器程序的Form1的文本框显示接收到的数据
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 = "";
}
}
}
一切正在发生的事情。在调试时,我确认了this.textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + m;
行的变量m
中收到的正确值。唯一的问题是,该值无法显示,因此在服务器程序的Form1上可见。
有人可以请帮忙。
你的文本框支持多行吗? –
@AlfieGoodacre对于服务器应用程序代码的Form1上的textBox1,Multiline被设置为'true'。是。 – Jogi
您的点击处理程序在'while(true)'循环中接收消息。它永远不会退出,然后控件永远不会有机会刷新(并且应用程序将挂起)。将它移动到一个'BackgroundWorker'。另一个_minor_事物:你不需要同时调用Dispose()和Close(),它可以用'using'来简化。我相信还有其他问题关于同样的问题(关闭这个像笨蛋),但现在找不到它 –