Browse Source

Stop thread when socket is closed

new_protocol
ThePerkinrex 5 years ago
parent
commit
ee250c7c85
No known key found for this signature in database GPG Key ID: FD81DE6D75E20917
  1. 12
      unity/Assets/Scripts/TcpConnection.cs

12
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);

Loading…
Cancel
Save