TcpClient没有连接,程序冻结,服务器没有收到任何东西

时间:2013-02-24 15:54:08

标签: c# tcp tcpclient

    static void tcp()
    {
        MessageBox.Show("Beginning...");
        System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("127.0.0.1");
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 20061);
        TcpClient connection = new TcpClient();
        connection.Connect(ipEndPoint);
        NetworkStream stream = connection.GetStream();
        var reader = new StreamReader(stream);
        var writer = new StreamWriter(stream);
        writer.WriteLine("/api/subscribe?source=console&key=d41c411558628535bbad927b1ad667c823e37a7e06e1b0a61ce707ed287bb4bb&show_previous=true");
        writer.Flush();
        var line = reader.ReadLine();
        if (line != "success")
            throw new InvalidOperationException("Failed to connect");
        while ((line = reader.ReadLine()) != null)
        {
            MessageBox.Show(line);
            Program.Form3 Form3 = new Program.Form3();
            Form3.textBox1.Text = Form3.textBox1.Text + "\r\n" + line;
        }
    }

这是我得到的代码。我想连接到我的服务器等待TCP上的请求。但是,这段代码不起作用,我无法弄清楚原因。当它在主线程上时,程序只是冻结了。现在,当它在另一个线程(tcp())上时,实际上什么也没发生,服务器甚至都没有收到任何东西。

我检查了服务器是否完全正常运行,100%正常工作。我使用SimpleTCP进行了检查。 (我通过端口20061连接到127.0.0.1,并发送命令“/ api / subscribe?source = console& key = d41c411558228535bbad927b1ad667c823e37a7e06e1b0a61ce707ed287bb4bb& show_previous = true”,并开始接收我想要的字符串。)

我只想连接到TCP,发送一个命令,然后开始接收字符串。

哦,我肯定会调用该帖子,当我按下“connect”按钮时,会显示消息框。

1 个答案:

答案 0 :(得分:1)

完成编写命令后尝试调用writer.Flush()。允许StreamWriter缓冲数据并在缓冲区满时写入。 Flush()刷新写缓冲区,这就是你想要的。