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,发送一个命令,然后开始接收字符串。
哦,我确实调用了线程,当我点击“连接”按钮时,消息框就会出现。