ugly hacked async connection

This commit is contained in:
Chris Forbes
2010-01-18 18:08:10 +13:00
parent b7c5b9e265
commit f6e70f74e3
4 changed files with 77 additions and 21 deletions

View File

@@ -3,9 +3,17 @@ using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System;
namespace OpenRa.Orders
{
enum ConnectionState
{
NotConnected,
Connecting,
Connected,
}
class NetworkOrderSource : IOrderSource
{
TcpClient socket;
@@ -13,35 +21,53 @@ namespace OpenRa.Orders
Dictionary<int, List<byte[]>> orderBuffers = new Dictionary<int, List<byte[]>>();
Dictionary<int, bool> gotEverything = new Dictionary<int, bool>();
public ConnectionState State { get; private set; }
public NetworkOrderSource(string host, int port)
{
socket = new TcpClient(host, port);
this.socket.NoDelay = true;
var reader = new BinaryReader(socket.GetStream());
State = ConnectionState.Connecting;
new Thread(() =>
socket = new TcpClient();
socket.BeginConnect(host, port, OnConnected, null);
socket.NoDelay = true;
}
void OnConnected(IAsyncResult r)
{
try
{
for (; ; )
socket.EndConnect(r);
State = ConnectionState.Connected;
new Thread(() =>
{
var len = reader.ReadInt32();
var frame = reader.ReadInt32();
var buf = reader.ReadBytes(len - 4);
lock (orderBuffers)
for (; ; )
{
if (len == 5 && buf[0] == 0xef) /* got everything marker */
gotEverything[frame] = true;
else
var reader = new BinaryReader(socket.GetStream());
var len = reader.ReadInt32();
var frame = reader.ReadInt32();
var buf = reader.ReadBytes(len - 4);
lock (orderBuffers)
{
/* accumulate this chunk */
if (!orderBuffers.ContainsKey(frame))
orderBuffers[frame] = new List<byte[]> { buf };
if (len == 5 && buf[0] == 0xef) /* got everything marker */
gotEverything[frame] = true;
else
orderBuffers[frame].Add(buf);
{
/* accumulate this chunk */
if (!orderBuffers.ContainsKey(frame))
orderBuffers[frame] = new List<byte[]> { buf };
else
orderBuffers[frame].Add(buf);
}
}
}
}
}) { IsBackground = true }.Start();
}) { IsBackground = true }.Start();
}
catch
{
State = ConnectionState.NotConnected;
}
}
static List<byte[]> NoOrders = new List<byte[]>();
@@ -66,7 +92,8 @@ namespace OpenRa.Orders
public void SendLocalOrders(int localFrame, List<Order> localOrders)
{
socket.GetStream().WriteFrameData(localOrders, localFrame);
if (socket.Connected)
socket.GetStream().WriteFrameData(localOrders, localFrame);
}
public bool IsReadyForFrame(int frameNumber)