Esempio n. 1
0
        private Buffer CreateValidBuffer()
        {
            var buff = CreateBuffer();

            Buffer.FinalizeBuffer(buff);
            return(buff);
        }
Esempio n. 2
0
        private void SendTestMessage(ISocket other, Buffer sendBuffer)
        {
            Buffer.ClearBuffer(sendBuffer);
            Buffer.Add(sendBuffer, 10);
            Buffer.Add(sendBuffer, 20.0F);
            Buffer.Add(sendBuffer, 40.0);
            Buffer.Add(sendBuffer, 'A');
            Buffer.Add(sendBuffer, "The quick brown fox jumped over the lazy dog");
            Buffer.Add(sendBuffer, (byte)255);
            Buffer.FinalizeBuffer(sendBuffer);

            var bytesSent = AweSock.SendMessage(other, sendBuffer);

            Console.WriteLine("Sent payload. {0} bytes written.", bytesSent);
        }
Esempio n. 3
0
        private void ListenForMessages(ISocket socket)
        {
            var callbackFired = new ManualResetEventSlim(false);
            var receiveBuffer = ASBuffer.New();

            while (!CancelToken.IsCancellationRequested)
            {
                ASBuffer.ClearBuffer(receiveBuffer);
                Tuple <int, EndPoint> result = null;
                try
                {
                    AweSock.ReceiveMessage(socket, receiveBuffer, AwesomeSockets.Domain.SocketCommunicationTypes.NonBlocking, (b, endPoint) =>
                    {
                        result = new Tuple <int, EndPoint>(b, endPoint); callbackFired.Set();
                    });
                }
                catch (ArgumentOutOfRangeException)
                { // Swallow the exception caused by AweSock's construction of an invalid endpoint
                }
                try
                {
                    callbackFired.Wait(CancelToken);
                }
                catch (OperationCanceledException)
                {
                }
                if (!CancelToken.IsCancellationRequested)
                {
                    callbackFired.Reset();
                    ASBuffer.FinalizeBuffer(receiveBuffer);
                    if (result.Item1 == 0)
                    {
                        return;
                    }

                    var length = ASBuffer.Get <short>(receiveBuffer);
                    var bytes  = new byte[length];
                    ASBuffer.BlockCopy(ASBuffer.GetBuffer(receiveBuffer), sizeof(short), bytes, 0, length);
                    MessageReceived?.Invoke(this, new MessageReceivedEventArgs()
                    {
                        Message = bytes
                    });
                }
            }
        }
Esempio n. 4
0
        public void ListenForMessages(ISocket socket)
        {
            var receiveBuffer = ASBuffer.New();

            while (!CancelToken.IsCancellationRequested)
            {
                ASBuffer.ClearBuffer(receiveBuffer);
                Tuple <int, EndPoint> result = null;
                try
                {
                    result = AweSock.ReceiveMessage(socket, receiveBuffer);
                }
                catch (SocketException)
                {
                    ClientSockets.TryRemove(socket, out byte _);
                    break;
                    // TODO: Determine which exceptions are intermittent and handle recovering before just bailing out
                }
                if (result.Item1 == 0)
                {
                    return;
                }
                var sendBuffer = ASBuffer.Duplicate(receiveBuffer);
                ASBuffer.FinalizeBuffer(sendBuffer);

                foreach (var client in ClientSockets.Keys)
                {
#if RELEASE
                    if (client != socket)
#endif
                    { // TODO: Does this work for displaying myself?
                        try
                        {
                            client.SendMessage(sendBuffer);
                        }
                        catch (SocketException)
                        {
                            // Swallow the exception trying to send, if it's not intermittent (connection closed etc) the receive message will throw and we handle it there (in another Task)
                        }
                    }
                }
            }
        }
Esempio n. 5
0
        public void SendMessage(ISynchroMessage message, ISocket connection)
        {
            Buffer.Resize(outBuf, message.GetLength() + sizeof(int));
            Buffer.Add(outBuf, message.GetLength());
            message.Serialize(outBuf);
            Buffer.FinalizeBuffer(outBuf);

            try
            {
                int bytesSent = AweSock.SendMessage(connection, outBuf);

                if (bytesSent == 0)
                {
                    throw new NetworkInformationException();
                }
            }
            catch (SocketException)
            {
                connections.Remove(connection);
            }
        }
Esempio n. 6
0
        public void SendModel(RemoteIDEModel model)
        {
            if (Socket != null)
            {
                using (var ms = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(ms, model);

                    var buffer = ASBuffer.New((int)ms.Length + sizeof(short));
                    ASBuffer.ClearBuffer(buffer);
                    // TODO: Remove AwesomeSocket and roll my own or find another because of crap like this
                    ASBuffer.Add(buffer, BitConverter.GetBytes((short)ms.Length).Concat(ms.ToArray()).ToArray());
                    ASBuffer.FinalizeBuffer(buffer);
                    try
                    {
                        Socket.SendMessage(buffer);
                    }
                    catch (Exception ex)
                    {
                        TeamCodingPackage.Current.Logger.WriteError(ex);
                    }
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// This method is called by the thread.
        /// </summary>
        public void Update()
        {
            while (this.mIsRunning)
            {
                // Check if the server must send data.
                if (this.mServer.PendingCommands.Any())
                {
                    // Clear all buffers.
                    foreach (var lNetBuffer in this.mNetBuffers)
                    {
                        AweBuffer.ClearBuffer(lNetBuffer.Value);
                    }

                    // Encode all commands.
                    foreach (var lCommand in this.mServer.PendingCommands)
                    {
                        if (string.IsNullOrWhiteSpace(lCommand.Value.ClientId))
                        {
                            foreach (var lClientView in this.mServer.Clients)
                            {
                                if (string.IsNullOrWhiteSpace(lClientView.Value.Id) == false)
                                {
                                    if (this.mNetBuffers.ContainsKey(lClientView.Value.Id) == false)
                                    {
                                        this.mNetBuffers.Add(lClientView.Value.Id, AweBuffer.New());
                                    }

                                    lCommand.Value.HasBeenEncoded = true;
                                    AweBuffer.Add(this.mNetBuffers[lClientView.Value.Id], lCommand.Value.Encode() + ";");
                                }
                            }
                        }
                        else
                        {
                            if (this.mNetBuffers.ContainsKey(lCommand.Value.ClientId) == false)
                            {
                                this.mNetBuffers.Add(lCommand.Value.ClientId, AweBuffer.New());
                            }
                            lCommand.Value.HasBeenEncoded = true;
                            AweBuffer.Add(this.mNetBuffers[lCommand.Value.ClientId], lCommand.Value.Encode() + ";");
                        }
                    }

                    foreach (var lNetBuffer in this.mNetBuffers)
                    {
                        AweBuffer.FinalizeBuffer(lNetBuffer.Value);
                    }

                    // Send data to each client.
                    bool lErrorOccured = false;
                    foreach (var lNetBuffer in this.mNetBuffers)
                    {
                        var lClient = this.mServer.Clients.FirstOrDefault(pClient => pClient.Value.Id == lNetBuffer.Key);
                        if (lClient.Value != null && lClient.Value.Status != Status.Lost)
                        {
                            try
                            {
                                AweSock.SendMessage(lClient.Value.Socket, lNetBuffer.Value);
                            }
                            catch
                            {
                                lErrorOccured = true;
                                Console.WriteLine("Lost client");
                                this.mServer.LostClient(lClient.Value);
                            }
                        }
                    }

                    // Notifies all commands.
                    if (lErrorOccured == false)
                    {
                        foreach (var lCommand in this.mServer.PendingCommands)
                        {
                            if (lCommand.Value.HasBeenEncoded)
                            {
                                this.mServer.NotifyCommandSent(lCommand.Value);
                            }
                        }
                    }
                }

                // Try to receive some data.

                foreach (var lClientView in this.mServer.Clients)
                {
                    try
                    {
                        StringBuilder lInBuffer = new StringBuilder();
                        if (lClientView.Value.Socket != null && lClientView.Value.Socket.GetBytesAvailable() != 0)
                        {
                            AweBuffer.ClearBuffer(this.mInBuffer);
                            Tuple <int, EndPoint> lReceived = AweSock.ReceiveMessage(lClientView.Value.Socket, this.mInBuffer);
                            if (lReceived.Item1 != 0)
                            {
                                lInBuffer.Append(AweBuffer.Get <string>(this.mInBuffer));

                                if (lInBuffer.Length != 0)
                                {
                                    this.mServer.Decode(lInBuffer.ToString(), lClientView.Value);
                                }
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Lost client");
                        this.mServer.LostClient(lClientView.Value);
                    }
                }


                //Console.WriteLine("[SERVER] Sleep");
                Thread.Sleep(1000);
            }

            //Console.WriteLine("[SERVER] LeaveThread");
        }
Esempio n. 8
0
        /// <summary>
        /// This method is called by the thread.
        /// </summary>
        public void Update()
        {
            while (this.mIsRunning)
            {
                if (this.mClient.Socket != null)
                {
                    // Clear output buffers.
                    AweBuffer.ClearBuffer(this.mOutBuffer);
                    AweBuffer.ClearBuffer(this.mInBuffer);

                    // Encode all commands.
                    StringBuilder lBuffer = new StringBuilder();
                    foreach (var lCommand in this.mClient.PendingCommands)
                    {
                        lCommand.ClientId = this.mClient.Id;
                        AweBuffer.Add(this.mOutBuffer, lCommand.Encode());
                        lBuffer.AppendLine(";"); // End of command.
                        lCommand.HasBeenEncoded = true;
                    }

                    AweBuffer.FinalizeBuffer(this.mOutBuffer);

                    // Send data to the server.
                    try
                    {
                        AweSock.SendMessage(this.mClient.Socket, this.mOutBuffer);
                    }
                    catch (Exception lEx)
                    {
                        this.mClient.LostServer();
                        break;
                    }

                    // Notifies all commands.
                    foreach (var lCommand in this.mClient.PendingCommands)
                    {
                        if (lCommand.HasBeenEncoded)
                        {
                            this.mClient.NotifyCommandSent(lCommand);
                        }
                    }

                    this.mClient.PendingCommands.Clear();

                    // Try to receive some data.
                    StringBuilder lInBuffer = new StringBuilder();
                    try
                    {
                        if (this.mClient.Socket.GetBytesAvailable() != 0)
                        {
                            Tuple <int, EndPoint> lReceived = AweSock.ReceiveMessage(this.mClient.Socket, this.mInBuffer);
                            if (lReceived.Item1 == 0)
                            {
                                lInBuffer.Append(AweBuffer.Get <string>(this.mInBuffer));
                            }
                        }
                    }
                    catch (Exception lEx)
                    {
                        this.mClient.LostServer();
                        break;
                    }

                    if (lInBuffer.Length != 0)
                    {
                        this.mClient.Decode(lInBuffer.ToString());
                    }
                }


                Console.WriteLine("[" + this.mClient.Id + "] Sleep");
                Thread.Sleep(1000);
            }

            Console.WriteLine("[" + this.mClient.Id + "] LeaveThread");
        }
Esempio n. 9
0
        public void FinalizeBuffer_DoesntThrowBufferFinalizedException_IfBufferIsAlreadyFinalized()
        {
            var testBuffer = CreateValidBuffer();

            Assert.DoesNotThrow(() => Buffer.FinalizeBuffer(testBuffer));
        }
Esempio n. 10
0
 public void FinalizeBuffer_ArgumentNullException_WhenBufferIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => Buffer.FinalizeBuffer(null));
 }
Esempio n. 11
0
        public void FinalizeBuffer_DoesntThrowBufferFinalizedException_IfBufferIsAlreadyFinalized()
        {
            var testBuffer = CreateValidBuffer();

            Buffer.FinalizeBuffer(testBuffer);
        }