From ee250c7c85f3bd501998a839eb486b00d5a9b8c1 Mon Sep 17 00:00:00 2001 From: ThePerkinrex Date: Thu, 15 Jul 2021 13:20:04 +0200 Subject: [PATCH] Stop thread when socket is closed --- unity/Assets/Scripts/TcpConnection.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/unity/Assets/Scripts/TcpConnection.cs b/unity/Assets/Scripts/TcpConnection.cs index 67dc89a..7728d0c 100644 --- a/unity/Assets/Scripts/TcpConnection.cs +++ b/unity/Assets/Scripts/TcpConnection.cs @@ -12,9 +12,13 @@ public class TcpConnection { private Thread receiverThread; private Protocol.ServerClientPacket Receive() { + byte[] b = new byte[4]; - c.Client.Receive(b, 0, 4, + int receivedBytes = c.Client.Receive(b, 0, 4, SocketFlags.None); + if (receivedBytes != 4) { + return null; + } if (!BitConverter.IsLittleEndian) { // Invert byte order, in order to get little endian byte order byte a = b[0]; @@ -27,6 +31,7 @@ public class TcpConnection { int size = BitConverter.ToInt32(b, 0); byte[] data = new byte[size]; c.Client.Receive(data, 0, size, SocketFlags.None); + Debug.Log("Recieved " + size + " bytes"); return Protocol.ServerClientPacket.Parser.ParseFrom(data); } @@ -34,8 +39,12 @@ public class TcpConnection { Debug.Log("Started receiver thread"); while(true) { Protocol.ServerClientPacket packet = Receive(); + if (packet == null) { + break; + } q.Enqueue(packet); } + Debug.Log("Stopped receiver thread"); } public void Close() { @@ -63,7 +72,6 @@ public class TcpConnection { sizeBytes[1] = sizeBytes[2]; sizeBytes[2] = a; } - Debug.Log("Size: " + size); c.Client.Send(sizeBytes); byte[] data = packet.ToByteArray(); c.Client.Send(data);