TcpClient没有';t连接,程序冻结,服务器没有接收到任何内容
本文关键字:任何内 服务器 程序 没有 TcpClient 连接 冻结 | 更新日期: 2023-09-27 18:00:55
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=d41c411558628535bbad927b1ad667c823e37a7e06e1b0a61ce707ed287bb4bb&show_previous=true",并开始接收我想要的字符串。(
我只想连接到TCP,发送一个命令,然后开始接收字符串。
哦,我确实调用了线程,当我点击"连接"按钮时,消息框就会出现。
完成命令编写后,请尝试调用writer.Flush()
。允许StreamWriter
缓冲数据,并在缓冲区已满时写入数据。Flush()
刷新写缓冲区,这正是您想要的。