我正在尝试在现有的 Windows 窗体应用程序中实现简单的 TCP/IP 通信。构成通信部分的代码有一个无限的while循环,我相信它会让服务器不断地监听客户端。它适用于我的应用程序,除了我对如何让它在单独的线程上运行有点卡住。我将在下面发布我的代码:
private TcpListener tcpListener;
private Thread listenThread;
private void Form1_Load(object sender, EventArgs e)
{
startServer();
}
private void startServer()
{
TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
listBox1.Items.Add(" >> Data from client - " + dataFromClient);
string serverResponse = "Server acknowledges the request - " + dataFromClient;
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
listBox1.Items.Add(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
我将不胜感激有关此问题的任何建议。谢谢!