我有这个代码:
private void startServer()
{
new Thread(() => StartListening()).Start();
}
void StartListening()
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(0, serverPort));
serverSocket.Listen(100);
Accept();
}
void Accept()
{
while (true)
{
acceptedMessages = serverSocket.Accept();
Buffer = new byte[acceptedMessages.SendBufferSize];
int bytesRead = acceptedMessages.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
string command = Encoding.ASCII.GetString(formatted);
string[] splittedCommand = command.Split(' ');
jobsHistory.Items.Add(Encoding.ASCII.GetString(formatted));
jobsHistory.Refresh();
Process processToRun = new Process();
processToRun.StartInfo.FileName = splittedCommand[0];
processToRun.StartInfo.WorkingDirectory = Path.GetDirectoryName(splittedCommand[0]);
processToRun.StartInfo.Arguments = "";
for (int i = 1; i < splittedCommand.Length; i++)
{
processToRun.StartInfo.Arguments += " " + splittedCommand[i];
}
processToRun.Start();
if (!isSocketConnected(serverSocket))
{
connectionStatusColor.BackColor = Color.Red;
isConnected = false;
startStopListnening.Text = "Listen";
break;
}
}
acceptedMessages.Shutdown(SocketShutdown.Both);
// If you want to start listening again
serverSocket.Shutdown(SocketShutdown.Both);
startServer();
}
当应用程序检测到客户端已断开连接时,我试图寻找一种安全关闭套接字的方法。
我看到了一些关于serverSocket.close()
和serverSocket.shutdown(SocketShutdown.Both);
但是每次客户端断开连接时,应用程序都会崩溃。
有任何想法吗?