如何使用TCP / IP协议连续监听Ip /端口的数据?

时间:2017-03-02 16:15:20

标签: c# tcpclient tcp-ip

我正在尝试开发一个程序(基本上是Windows服务)来持续监听设备将使用telnet以30秒的间隔发送数据的IP和PORT。

现在,我已经google了很多,据我所知,TCPClient或TCPListener可用于从telnet接收数据。我在互联网上经历了一些解决方案,但大多数都是一次写入和读取解决方案,但我需要不断地听取IP。我不必发送任何内容只是监听数据并将其保存在SQL SERVER DB中(我已完成此代码)。以下是我尝试的客户端代码:

    private void Form1_Load(object sender, EventArgs e)
    {
        msg("Client Started");
        clientSocket.Connect(IPAdd, 23);
        label1.Text = "Client Socket Program - Server Connected ...";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        NetworkStream serverStream = clientSocket.GetStream();

        StreamReader objstream = new StreamReader(path, UnicodeEncoding.Unicode);
        //textBox1.Text = objstream.ReadLine();

        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(objstream.ReadToEnd() + "$");
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();

        byte[] inStream = new byte[clientSocket.ReceiveBufferSize];
        serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);
        msg(returndata);
        textBox2.Text = "";
        textBox2.Focus();

        string path = @"D:\TELNETResponse.txt";
        if (!File.Exists(path))
        {
            File.Create(path);
            TextWriter tw = new StreamWriter(path);
            tw.WriteLine(returndata);
            tw.Close();
        }
        else if (File.Exists(path))
        {
            using (var tw = new StreamWriter(path, true))
            {
                tw.WriteLine(returndata);
                tw.Close();
            }
        }
    }

在这方面的任何帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

所以你想要做的是设置一个while循环,如果你想连续监听,这是这个应用程序唯一的操作。您的代码应如下所示:

private void button1_Click(object sender, EventArgs e)
{
    string data;
    NetworkStream serverStream = clientSocket.GetStream();
    StreamReader streamReader = new StreamReader(serverStream, Encoding.Default);
    string path = @"D:\TELNETResponse.txt";
    if (!File.Exists(path))
    {
        File.Create(path);
        TextWriter tw = new StreamWriter(path);
        tw.WriteLine(returndata);
        tw.Close();
    }
    while ((data = streamReader.ReadLine()) != null) 
    {
        using (var tw = new StreamWriter(path, true))
        {
            tw.WriteLine(returndata);
            tw.Close();
        }
    }
}

如果连接断开,streamReader将只会变为NULL,此时您需要设置一些代码才能重新连接。