You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
80 lines
2.0 KiB
80 lines
2.0 KiB
using System.IO;
|
|
using System.Net.Sockets;
|
|
using System.Collections.Concurrent;
|
|
using System.Threading;
|
|
using System;
|
|
using Google.Protobuf;
|
|
using UnityEngine;
|
|
|
|
public class TcpConnection {
|
|
private TcpClient c;
|
|
public ConcurrentQueue<Protocol.ServerClientPacket> q;
|
|
private Thread receiverThread;
|
|
|
|
private Protocol.ServerClientPacket Receive() {
|
|
|
|
byte[] b = new byte[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];
|
|
b[0] = b[3];
|
|
b[3] = a;
|
|
a = b[1];
|
|
b[1] = b[2];
|
|
b[2] = a;
|
|
}
|
|
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);
|
|
}
|
|
|
|
private void ReceiverThread() {
|
|
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() {
|
|
receiverThread.Join();
|
|
}
|
|
|
|
public TcpConnection(string address) {
|
|
string[] ipAndPort = address.Split(':');
|
|
c = new TcpClient(ipAndPort[0], int.Parse(ipAndPort[1]));
|
|
q = new ConcurrentQueue<Protocol.ServerClientPacket>();
|
|
receiverThread = new Thread(new ThreadStart(ReceiverThread));
|
|
Debug.Log("Starting receiver thread");
|
|
receiverThread.Start();
|
|
}
|
|
|
|
public void SendMessage(Protocol.ClientServerPacket packet) {
|
|
int size = packet.CalculateSize();
|
|
byte[] sizeBytes = BitConverter.GetBytes(size);
|
|
if (!BitConverter.IsLittleEndian) {
|
|
// Invert byte order, in order to get little endian byte order
|
|
byte a = sizeBytes[0];
|
|
sizeBytes[0] = sizeBytes[3];
|
|
sizeBytes[3] = a;
|
|
a = sizeBytes[1];
|
|
sizeBytes[1] = sizeBytes[2];
|
|
sizeBytes[2] = a;
|
|
}
|
|
c.Client.Send(sizeBytes);
|
|
byte[] data = packet.ToByteArray();
|
|
c.Client.Send(data);
|
|
}
|
|
|
|
}
|