Beispiel #1
0
        /// <summary>
        /// Starts the agent.
        /// </summary>
        /// <param name="pServerAdress">The server adress.</param>
        /// <param name="pServerPort">The server port.</param>
        /// <param name="pClientId">The client identifier.</param>
        public void Start(string pServerAdress, int pServerPort, string pClientId)
        {
            try
            {
                this.mServerAdress = pServerAdress;
                this.mServerPort   = pServerPort;
                this.Id            = pClientId;
                this.Socket        = AweSock.TcpConnect(pServerAdress, pServerPort);

                this.mHandler = new AgentClientHandler(this, this.mReconnectIndex);
                this.mThread  = new Thread(this.mHandler.Update)
                {
                    Name = "Client " + this.mReconnectIndex
                };
                this.mThread.Start();
                this.mReconnectIndex++;
                this.mReconnectionTimer.Enabled = false;

                this.Send(new DeclareClient(pClientId));
            }
            catch
            {
                Console.WriteLine("[" + this.Id + "] Try to reconnect");
                this.mReconnectionTimer.Enabled = true;
            }
        }
Beispiel #2
0
        public void ReceiveNextMessage(bool skipConnectingEvents, ISocket connection, ISynchroMessage targetMessage)
        {
            try
            {
                Buffer.Resize(inBuf, sizeof(int));
                AweSock.ReceiveMessage(connection, inBuf);
                int messageLength = Buffer.Get <int>(inBuf);

                Buffer.Resize(inBuf, messageLength);
                int received = 0;

                do
                {
                    received += AweSock.ReceiveMessage(connection, inBuf, received);
                    if (received == 0)
                    {
                        throw new SocketException();
                    }
                } while (received < messageLength);

                targetMessage.Deserialize(inBuf);
            }
            catch (SocketException)
            {
                connections.Remove(connection);
            }
        }
Beispiel #3
0
        public override void Connect()
        {
            int tryCounter = 0;

nextTry:
            try
            {
                connections.Add(AweSock.TcpConnect(NodeInformation.master.ip, NodeInformation.master.port + 1));
            }
            catch (Exception)
            {
                Debug.Log("Could not connect to server. Trying again.");

                if (++tryCounter >= 10)
                {
#if UNITY_EDITOR
                    UnityEditor.EditorApplication.isPlaying = false;
#else
                    Application.Quit();
#endif
                    return;
                }

                Thread.Sleep(500);
                goto nextTry;
            }
            InitializeSelf();
        }
Beispiel #4
0
 private void button1_Click(object sender, System.EventArgs e)
 {
     if (_serverSocket != null)
     {
         _serverSocket.Close();
     }
     _serverSocket = AweSock.TcpConnect(ipTextBox.Text, int.Parse(portTextBox.Text));
 }
 public ISocket Apply(ISocket socket)
 {
     //TODO: Need to check if socket is UDP as Multicast only works with UDP...
     AweSock.SetSockOpt(socket, new Dictionary <SocketOptionName, object>
     {
         { SocketOptionName.AddMembership, new MulticastOption(_multicastIpAddress, IPAddress.Parse("127.0.0.1")) }
     });
     return(socket);
 }
Beispiel #6
0
 public override void Connect()
 {
     listenSocket = AweSock.TcpListen(NodeInformation.own.port + 1);
     while (connections.Count < targetClientNumber)
     {
         connections.Add(AweSock.TcpAccept(listenSocket));
         InitializeClient(connections[connections.Count - 1]);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Starts the agent.
        /// </summary>
        public void Start(int pPort)
        {
            this.ListenSocket = AweSock.TcpListen(pPort);
            AweSock.TcpAccept(this.ListenSocket, SocketCommunicationTypes.NonBlocking, this.NewClient);

            this.mHandler = new AgentServerHandler(this);
            this.mThread  = new Thread(this.mHandler.Update);
            this.mThread.Start();
        }
Beispiel #8
0
        private void ServerThread(Action <bool> callback)
        {
            var sendBuffer   = Buffer.New();
            var recvBuffer   = Buffer.New();
            var listenSocket = AweSock.TcpListen(14804);
            var client       = AweSock.TcpAccept(listenSocket);

            SendTestMessage(client, sendBuffer);
            callback(ReceiveResponseFromClient(client, recvBuffer));
        }
Beispiel #9
0
        public void ClientThread(Action <bool> callback)
        {
            Buffer sendBuffer = Buffer.New();
            Buffer recvBuffer = Buffer.New();

            ISocket server = AweSock.TcpConnect("127.0.0.1", 14804);

            ReceiveMessageFromServer(server, recvBuffer);
            SendTestMessage(server, sendBuffer);
            callback(true);
        }
Beispiel #10
0
        void Listen()
        {
            syncServer = AweSock.TcpListen(port);
            Thread.Sleep(3000);
            Log.Notice("Master Server is listening on {0}:{1}", ip, port);

            while (true)
            {
                var client   = AweSock.TcpAccept(syncServer);
                var receiver = new IPCReceiver(client, this);
            }
        }
Beispiel #11
0
 bool SendIPC(AwesomeSockets.Buffer packet)
 {
     try
     {
         AweSock.SendMessage(socket, packet);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Beispiel #12
0
 bool ReadIPC(AwesomeSockets.Buffer packet)
 {
     try
     {
         AweSock.ReceiveMessage(syncClient, packet);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Beispiel #13
0
 private void StartServer(int serverPort)
 {
     if (_listenSocket != null)
     {
         _listenSocket.Close();
         _listenSocket = null;
     }
     _listenSocket = AweSock.TcpListen(serverPort);
     //Non-blocking mode
     AweSock.TcpAccept(_listenSocket, SocketCommunicationTypes.NonBlocking, AcceptClient);
     _logger.Info($"Listening on port: {serverPort}");
 }
Beispiel #14
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);
        }
Beispiel #15
0
        /// <summary>
        /// This method is called each time a new client is connected.
        /// </summary>
        /// <param name="pClientSocket">The client socket.</param>
        /// <param name="pError">The error during connection.</param>
        /// <returns></returns>
        private Socket NewClient(ISocket pClientSocket, Exception pError)
        {
            if (pClientSocket?.GetSocket() != null)
            {
                AweSock.TcpAccept(this.ListenSocket, SocketCommunicationTypes.NonBlocking, this.NewClient);
                ClientView lClientView = new ClientView()
                {
                    Socket = pClientSocket
                };
                this.Clients.TryAdd(lClientView, lClientView);
                this.ClientConnected?.Invoke(this, lClientView, null);
                return(pClientSocket.GetSocket());
            }

            return(null);
        }
Beispiel #16
0
 void ReceiveThread()
 {
     while (true)
     {
         AwesomeSockets.Buffer.ClearBuffer(recvBuffer);
         try
         {
             AweSock.ReceiveMessage(socket, recvBuffer);
             PipeServer.ProcessPacket(this, recvBuffer);
         }
         catch (Exception)
         {
             rThread.Abort();
         }
     }
 }
Beispiel #17
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
                    });
                }
            }
        }
Beispiel #18
0
        void Listen()
        {
            Thread.Sleep(1000);
            Log.Notice("Starting sync connection with Master Server...");
            Thread.Sleep(1000);

            hbTimer           = new System.Timers.Timer(1000 * 36); // heartbeat every 30 seconds
            hbTimer.AutoReset = true;
            hbTimer.Elapsed  += (sender, e) => { HeartBeat(); };

            while (true)
            {
                if (syncClient == null && !syncRunning)
                {
                    try
                    {
                        syncClient  = AweSock.TcpConnect(ip, port);
                        syncRunning = true;
                        hbTimer.Start();
                        Log.Notice("Established sync connection with Master Server!");
                        SyncSuccess(this, new EventArgs());
                    }
                    catch (Exception)
                    {
                        syncRunning = false;
                        Log.Error("Failed to establish sync connection to Master Server!", "[ObjectBuddy::SyncReceiver::Listen()]");
                        SyncFailed(this, new EventArgs());
                    }
                }

                if (syncRunning)
                {
                    if (!syncClient.GetSocket().Connected)
                    {
                        hbTimer.Stop();
                        syncClient  = null;
                        syncRunning = false;
                        Log.Error("Lost sync connection to Master Server!", "[ObjectBuddy::SyncReceiver::Listen()]");
                    }
                }

                Thread.Sleep(1);
            }
        }
        private static void ReceiveMessageFromServer(ISocket server, Buffer recvBuffer)
        {
            var clientExitFlag = false;

            do
            {
                var(item1, _) = AweSock.ReceiveMessage(server, recvBuffer);
                if (item1 > 0)
                {
                    clientExitFlag = true;
                }
                else if (item1 == 0)
                {
                    return;
                }

                Thread.Sleep(1000);
            } while (!clientExitFlag);
        }
Beispiel #20
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)
                        }
                    }
                }
            }
        }
Beispiel #21
0
        public void ListenForConnections()
        {
            var taskFactory = new TaskFactory();

            ListenSocket = AweSock.TcpListen(ListenPort);
            while (!CancelToken.IsCancellationRequested)
            {
                try
                {
                    var clientSocket = AweSock.TcpAccept(ListenSocket);
                    ClientSockets.TryAdd(clientSocket, 0);
                    var listenTask = new Task(() => ListenForMessages(clientSocket), TaskCreationOptions.LongRunning);
                    listenTask.ContinueWith(t =>
                    {
                        lock (ListenTasks)
                        {
                            ListenTasks.Remove(t);
                        }
                    }).ConfigureAwait(false);
                    lock (ListenTasks)
                    {
                        ListenTasks.Add(listenTask);
                    }
                    listenTask.Start();
                }
                catch (SocketException)
                {
                    if (!CancelToken.IsCancellationRequested)
                    {
                        try
                        {
                            // Try and re-connect.
                            Thread.Sleep(1000);
                            ListenSocket = AweSock.TcpListen(ListenPort);
                        }
                        catch (SocketException)
                        {
                        }
                    }
                }
            }
        }
Beispiel #22
0
        private async Task ListenInternalAsync()
        {
            try
            {
                if (await IPAddressSetting.IsValidAsync())
                {
                    Socket = AweSock.TcpConnect(IPAddressSetting.Value.Split(':')[0], int.Parse(IPAddressSetting.Value.Split(':')[1]));
                    ListenForMessages(Socket);
                }
            }
            catch (SocketException)
            {
                await Task.Delay(1000);

                if (!CancelToken.IsCancellationRequested)
                {
                    // TODO: Handle socket exception (try and re-connect after a while?)
                }
            }
        }
Beispiel #23
0
        private bool ReceiveMessageFromServer(ISocket server, Buffer recvBuffer)
        {
            bool CLIENT_EXIT_FLAG = false;

            do
            {
                var bytesReceived = AweSock.ReceiveMessage(server, recvBuffer);
                if (bytesReceived.Item1 > 0)
                {
                    CLIENT_EXIT_FLAG = true;
                }
                else if (bytesReceived.Item1 == 0)
                {
                    return(false);
                }

                Thread.Sleep(1000);
            } while (!CLIENT_EXIT_FLAG);
            return(true);
        }
Beispiel #24
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);
            }
        }
Beispiel #25
0
        void ReceiveThread()
        {
            while (true)
            {
                AwesomeSockets.Buffer.ClearBuffer(recvBuffer);
                try
                {
                    AweSock.ReceiveMessage(socket, recvBuffer);
                    var reader = new IPCReader(recvBuffer);
                    var packet = reader.Opcode;

                    ipc.HandlePacket(this, reader, packet);
                }
                catch (Exception)
                {
                    if (serverId > 0 && channelId > 0)
                    {
                        ipc.RemoveChannel(serverId, channelId); // let's remove channel from list
                    }
                    rThread.Abort();
                }
            }
        }
Beispiel #26
0
        private bool ReceiveResponseFromClient(ISocket client, Buffer recvBuffer)
        {
            bool SERVER_EXIT_FLAG = false;

            do
            {
                var bytesReceived = AweSock.ReceiveMessage(client, recvBuffer);
                if (bytesReceived.Item1 > 0)
                {
                    if (!ValidateResponse(recvBuffer))
                    {
                        return(false);
                    }
                    SERVER_EXIT_FLAG = true;
                }
                else if (bytesReceived.Item1 == 0)
                {
                    return(false);
                }

                //Thread.Sleep(1000);
            } while (!SERVER_EXIT_FLAG);
            return(true);
        }
Beispiel #27
0
        void Listen()
        {
            Thread.Sleep(1000);
            Log.Notice("Starting Sync with the Master Server");
            Thread.Sleep(1000);

            while (true)
            {
                if (syncClient == null && !syncRunning)
                {
                    try
                    {
                        syncClient  = AweSock.TcpConnect(ip, port);
                        syncRunning = true;
                        Log.Notice("Established Sync connection to the Master Server");
                        SyncSuccess(this, new EventArgs());
                    }
                    catch (Exception)
                    {
                        syncRunning = false;
                        Log.Error("Sync with the Master Server failed!");
                    }
                }

                if (syncRunning)
                {
                    if (!syncClient.GetSocket().Connected)
                    {
                        syncClient  = null;
                        syncRunning = false;
                    }
                }

                Thread.Sleep(1);
            }
        }
        private bool ReceiveResponseFromClient(ISocket client, Buffer recvBuffer)
        {
            var serverExitFlag = false;

            do
            {
                var(item1, _) = AweSock.ReceiveMessage(client, recvBuffer);
                if (item1 > 0)
                {
                    if (!ValidateResponse(recvBuffer))
                    {
                        return(false);
                    }
                    serverExitFlag = true;
                }
                else if (item1 == 0)
                {
                    return(false);
                }

                //Thread.Sleep(1000);
            } while (!serverExitFlag);
            return(true);
        }
Beispiel #29
0
        public async Task StartClient(Trainer trainer)
        {
            //Request server IP and port number
            Console.WriteLine("Please enter the server IP in the format 192.168.0.1 and press return:");
            string ip = Console.ReadLine();

            Console.WriteLine("Please enter the server port and press return:");
            string port = Console.ReadLine();

            ISocket server = AweSock.TcpConnect(ip, int.Parse(port));

            var inBuf  = AwesomeSockets.Buffers.Buffer.New(99999);
            var outBuf = AwesomeSockets.Buffers.Buffer.New(99999);

            this.SetupClientTrainer(trainer);

            while (true)
            {
                try
                {
                    //get data
                    var outputData = this.GetOutputData(trainer);

                    //write data to buffer
                    AwesomeSockets.Buffers.Buffer.ClearBuffer(outBuf);
                    AwesomeSockets.Buffers.Buffer.Add(outBuf, Utils.ObjectToByteArray(outputData));
                    AwesomeSockets.Buffers.Buffer.FinalizeBuffer(outBuf);

                    //send data
                    int bytesSent = AweSock.SendMessage(server, outBuf);
                    Console.WriteLine("sent data");

                    //get response
                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();

                    Tuple <int, EndPoint> received = AweSock.ReceiveMessage(server, inBuf);
                    stopWatch.Stop();

                    TimeSpan ts = stopWatch.Elapsed;
                    trainer.timeSinceUpdate = ts.Milliseconds;

                    AwesomeSockets.Buffers.Buffer.FinalizeBuffer(inBuf);

                    //parse response
                    var res = Utils.Deserialize <Dictionary <string, byte[]> >(AwesomeSockets.Buffers.Buffer.GetBuffer(inBuf));
                    AwesomeSockets.Buffers.Buffer.ClearBuffer(inBuf);

                    //act on response
                    //Console.WriteLine(string.Join(", ", res["pos_ally"]));
                    this.HandleInputData(res, trainer);

                    //refresh rate
                    Thread.Sleep(50);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);

                    AwesomeSockets.Buffers.Buffer.ClearBuffer(outBuf);
                    AwesomeSockets.Buffers.Buffer.ClearBuffer(inBuf);

                    trainer.Initialize();
                    Thread.Sleep(50);
                }
            }
        }
Beispiel #30
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");
        }