Exemple #1
0
    public string Accept()
    {
        if (!listener.IsActive())
        {
            tokenSource.Cancel();
        }
        tokenSource.Token.ThrowIfCancellationRequested();
        TcpClient client = null;

        try {
            client = listener.AcceptTcpClient();
        } catch (Exception io) {
            Debug.Log("accept aborted");
            Debug.Log(io);
            tokenSource.Cancel();
        }
        tokenSource.Token.ThrowIfCancellationRequested();
        var cancelClient = new CancelableTcpClient(client);
        var guid         = Guid.NewGuid().ToString();

        clients.Add(guid, cancelClient);
        cancelClient.GetCancellationTokenSource().Token.Register(() => {
            if (clients.ContainsKey(guid))
            {
                clients.Remove(guid);
            }
        });
        return(guid);
    }
Exemple #2
0
    public static MessageSubscription Read(
        CancelableTcpClient client,
        MonoBehaviour parent,
        MessageTransferLookUp lookUp
        )
    {
        var crossThread = new ConnectionReadCrossThread(parent, lookUp, client.GetCancellationTokenSource());

        byte[] readBuffer = new byte[ushort.MaxValue];
        var    dataStream = new MemoryStream(readBuffer);
        var    reader     = new BinaryReader(dataStream);

        Task.Factory.StartNew(() => {
            while (true)
            {
                dataStream.Position        = 0;
                reader.BaseStream.Position = 0;
                int read = 0;
                while (read < 4)
                {
                    read = read + client.Read(readBuffer, read, 4 - read);
                }
                var dataLength = reader.ReadUInt16();
                var opCode     = reader.ReadUInt16();
                while (read < 4 + dataLength)
                {
                    read = read + client.Read(readBuffer, read, (dataLength + 4) - read);
                }
                var data = lookUp.Deserialize(opCode, reader);
                crossThread.Recieve(opCode, data);
            }
        }, client.GetCancellationTokenSource().Token).ContinueWith((task) => {
            Debug.LogError("exception in task");
            Debug.LogError(task.Exception);
        }, TaskContinuationOptions.OnlyOnFaulted);
        return(crossThread);;
    }