没有永久连接到端口

时间:2019-02-22 05:55:02

标签: port tcpclient

我的计算机上有一个设备,我想从端口2005读取数据

我使用以下代码从2005端口读取数据。

    public MainWindow()
  {
            try
            {

                IPAddress localAddr = IPAddress.Parse("0.0.0.0");

                var host = Dns.GetHostEntry(Dns.GetHostName());

                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        localAddr = IPAddress.Parse(ip.ToString());
                    }
                }

                TcpClient client = null;
                try
                {
                    client = new TcpClient(localAddr.ToString(), 2005);
                }
                catch (SocketException se)
                {
                }


                Byte[] bytes = new Byte[256];
                String data = null;

                while (true)
                {
                    data = null;

                    NetworkStream stream = client.GetStream();

                    int i;

                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {                       
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                        DecodeReceivedMsg(data);                       
                    }

                    client.Close();
                }
            }
            catch (SocketException e)
            {

            }
            finally
            {

            }    
 }

我的问题是我不总是读取端口,而且很多时候while(true)无法运行。

请指导我

0 个答案:

没有答案