控制台程序和windows窗体下的同步通信
在控制台程序中用下面这段代码可以不断的接收送至端口的数据static void Main(string[] args)
{
Console.WriteLine("Sever is running...");
IPAddress ip = new IPAddress(new byte[] {192,168,2,68});
TcpListener listener = new TcpListener(ip,3000);
listener.Start();
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
while (true)
{
byte[] data = new byte[tcpClient.ReceiveBufferSize];
int numBytesRead = ns.Read(data, 0, System.Convert.ToInt32(tcpClient.ReceiveBufferSize));
Console.WriteLine(Encoding.ASCII.GetString(data, 0, numBytesRead));
}
但是在windows窗体中把这个代码做成一个函数,然后用button调用这个函数使其在文本中显示就不可以,窗体始终没有响应,这是什么原因?
private void ReceiveData()
{
IPAddress ip = new IPAddress(new byte[] {192,168,2,68});
TcpListener listener = new TcpListener(ip,3000);
listener.Start();
TcpClient tcpClient = listener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
while (true)
{
byte[] data = new byte[tcpClient.ReceiveBufferSize];
int numBytesRead = ns.Read(data, 0, System.Convert.ToInt32(tcpClient.ReceiveBufferSize));
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, numBytesRead));
string msg=Encoding.ASCII.GetString(data,0,numBytesRead);
textBoxTheDataReceived.Text = msg;
}
}
private void buttonConnectVision_Click(object sender, EventArgs e)
{
ReceiveData();
}