标题:控制台程序和windows窗体下的同步通信
取消只看楼主
hellold77
Rank: 1
等 级:新手上路
帖 子:4
专家分:0
注 册:2006-5-30
 问题点数:0 回复次数:0 
控制台程序和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();
         }
搜索更多相关主题的帖子: 通信 
2011-09-26 14:58



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-350922-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.065286 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved