Я разрабатываю приложение Unity, которое требует TCP -сервера. Я новичок в C#, и когда я внедрил TCP -сервер, я использовал следующий код, который изменен из того, что я нашел в Интернете. public static bool StartServer(int port, ITcpServer serverComm){
serverSocket = new TcpListener(IPAddress.Any,port);
keepServerAlive = true;
RxBuffer = new byte[1024];
comm = serverComm; // Just an interface for notifying of data received.
try {
serverSocketThread = new Thread( new ThreadStart(OnClientDataReceived) );
serverSocketThread.IsBackground = true;
serverSocket.Start();
serverSocketThread.Start();
}
catch (Exception e){
VMLog.error("Failed to start TCP Server. Reason: " + e.Message); // Basically the same same thing as Debug.Log for this question.
return false;
}
connectionStatus = ConnectionStatus.CONNECTING;
return true;
}
< /code>
и функция OnclientDatareceived выглядит так: < /p>
private static void OnClientDataReceived(){
try {
UnityEngine.Debug.Log("[TCP] Inside the try");
while (keepServerAlive){
UnityEngine.Debug.Log("[TCP] Inside the keep server alive");
using (client = serverSocket.AcceptTcpClient()) {
UnityEngine.Debug.Log("[TCP] Inside the accept TCP Clent");
// Get a stream object for reading
using (NetworkStream stream = client.GetStream()) {
int length;
//UnityEngine.Debug.Log("Connected and waiting for incoming bytes");
UnityEngine.Debug.Log("[TCP] Inside the Get Stream");
// Read incoming stream into byte array.
while ( ((length = stream.Read(RxBuffer, 0, RxBuffer.Length)) != 0) && keepServerAlive) {
connectionStatus = ConnectionStatus.CONNECTED; // If we are getting data, we are connected.
UnityEngine.Debug.Log("[TCP] Received " + length + " bytes");
comm.dataReceived(length);
}
UnityEngine.Debug.Log("[TCP] After the while in the stream read");
keepServerAlive = false;
}
}
}
VMLog.log("TCP Listening stopped naturally");
connectionStatus = ConnectionStatus.NOT_CONNECTED;
comm.rxThreadIsDone();
}
catch (Exception e){
VMLog.error("Listening thread died. Reason: " + e.Message);
connectionStatus = ConnectionStatus.NOT_CONNECTED;
comm.rxThreadIsDone();
}
}
< /code>
Вопрос: как я могу изменить код Ondatareceed, чтобы иметь возможность вручную убить его без необходимости вызвать метод Thread.abort (), и я не могу понять, как. Я не вижу, куда я могу положить логическое, которое постоянно проверяется, и когда его значение неверно, поток естественным образом умирает.
Подробнее здесь: https://stackoverflow.com/questions/789 ... -a-boolean