这是我通过通过套接字连接的客户端获取数据的代码,但我的数据获取的是表单标题而不是文本框。
// Buffer for reading data
Byte[] bytes = new Byte[4096];
String data = null;
//Enter the listening loop
while (true)
{
txtOutput.Text = "Waiting For Connection... to get started";
//blocks until a client is connected to server
TcpClient tcpClient = server.AcceptTcpClient();
txtOutput.Text = "Connected!..";
data = null;
// Get a stream object for reading and writing
NetworkStream netStream = tcpClient.GetStream();
int i;
//loop to receive all data sent by the client
while ((i = netStream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
//data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//txtOutput.Text = data;
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(bytes, 0, 4096));
Text += "\n" + Encoding.Default.GetString(bytes,0,i);
txtOutput.Invoke(new Action(() => txtOutput.Text += text));
}
// Shutdown and end connection
tcpClient.Close();
}
答案 0 :(得分:1)
更新
请注意,在调用之前,您正在将数据分配给Text
。在调用内部,您试图将text
的内容分配给文本框。这不是同一回事。更改以表格的Text属性为目标的以下行,如下所示:
// Text += "\n" + Encoding.Default.GetString(bytes,0,i);
text += "\n" + Encoding.Default.GetString(bytes,0,i);
在此行中分配给文本框时
txtOutput.Invoke(new Action(() => txtOutput.Text += text));
您是从text
变量(小T)而不是放置值的Text
(大T)分配的。大T Text是表单的Text属性,并且将按照您在此处所说的更改表格标题。