Esempio n. 1
0
        public IEnumerable <Common.ISerializable> Parse(CommandSerializer cs)
        {
            if (data == null)
            {
                yield break;
            }
            var packages = new List <ArraySegment <byte> >();

            using (var stream = new MemoryStream(data))
            {
                var ps = new PackageSerializer();
                ps.Package += (s, e) => packages.Add(e.Data);
                ps.Run(stream);
            }

            foreach (var p in packages)
            {
                using (var mem = new MemoryStream(p.Array, p.Offset, p.Count, false))
                {
                    var cmd = cs.DeserializeCommand(mem);
                    if (cmd != null)
                    {
                        yield return(cmd);
                    }
                }
            }
        }
Esempio n. 2
0
        private void Listen()
        {
            var endPoint = new IPEndPoint(IPAddress.Any, port);

            while (active)
            {
                if (client.Available > 0)
                {
                    byte[] data = client.Receive(ref endPoint);
                    using (var ms = new MemoryStream(data))
                    {
                        IPackage package = PackageSerializer.DeserializeFrom <IPackage>(ms);

                        SystemPackage systemPackage = package as SystemPackage;
                        if (systemPackage != null)
                        {
                            if (typeof(UdpMessage).IsAssignableFrom(systemPackage.ContentType))
                            {
                                UdpMessage udpMessage = systemPackage.DeserializeContent <UdpMessage>();

                                if (udpMessage.IsConnectMessage)
                                {
                                    this.SendNotification(new NotificationMessage(NotificationType.ClientConnect), connections.ToArray());

                                    this.SendNotification(new NotificationMessage(NotificationType.ClientList), connections.ToArray());
                                }
                                else
                                {
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 3
0
 /// <summary>
 /// Sends a package to the given receivers.
 /// </summary>
 /// <param name="package">The Package.</param>
 public void Send(IBasePackage package)
 {
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(package, mStream);
         _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563));
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Handles a connection.
        /// </summary>
        /// <param name="objConnection">The Connection.</param>
        private void HandleClient(object objConnection)
        {
            var           localConnection = (LocalConnection)objConnection;
            NetworkStream networkStream   = localConnection.Client.GetStream();

            while (localConnection.Connected)
            {
                if (localConnection.Client.Available > 0)
                {
                    //Reset idle
                    _idleTimeout = 0;
                    _currentIdle = 0;
                    IBasePackage package       = PackageSerializer.Deserialize(networkStream);
                    var          binaryPackage = package as BinaryPackage;
                    if (binaryPackage != null)
                    {
                        //notify package listeners
                        foreach (IPackageListener subscriber in GetPackageSubscriber(binaryPackage.OriginType))
                        {
                            subscriber.OnPackageReceived(binaryPackage);
                        }

                        //The package is not a system package, send it to it's destination
                        if (binaryPackage.Receiver == null)
                        {
                            //Send to all Clients
                            Send(binaryPackage);
                        }
                        else
                        {
                            //Special destination
                            Send(binaryPackage, binaryPackage.Receiver);
                        }
                        return;
                    }

                    //system package with type of pingpackage
                    var pingPackage = package as PingPackage;
                    if (pingPackage != null)
                    {
                        SetLatency(pingPackage);
                        return;
                    }
                }
                else
                {
                    Idle();
                }
            }

            //Client exited.
            SendNotificationPackage(NotificationMode.ClientExited,
                                    new IConnection[] { SerializableConnection.FromIConnection(localConnection) });
            _connections.Remove(localConnection);

            IConnection[] connectionList = SerializableConnection.FromIConnection(_connections.ToArray());
            SendNotificationPackage(NotificationMode.ClientList, connectionList);
        }
Esempio n. 5
0
        /// <summary>
        /// Sends a package to a specified client.
        /// </summary>
        /// <param name="package">The Package.</param>
        /// <param name="connection">The Connection</param>
        private void SendTo(IBasePackage package, IPAddress connection)
        {
            LocalConnection localConnection = GetConnection(connection);

            if (localConnection != null)
            {
                PackageSerializer.Serialize(package, localConnection.Client.GetStream());
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Sends a package to the given receivers.
 /// </summary>
 /// <param name="package">The Package.</param>
 /// <param name="receiver">The Receiver.</param>
 public void Send(IBasePackage package, IPAddress receiver)
 {
     package.Receiver = receiver;
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(package, mStream);
         _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563));
     }
 }
Esempio n. 7
0
 /// <summary>
 /// Sends a package to the given receivers.
 /// </summary>
 /// <param name="package">The Package.</param>
 /// <param name="receiver">The Receiver.</param>
 public void Send(IBasePackage package, IPAddress receiver)
 {
     byte[] result;
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(package, mStream);
         result = mStream.ToArray();
     }
     _listener.Client.SendTo(result, new IPEndPoint(receiver, 2565));
 }
Esempio n. 8
0
 /// <summary>
 /// Sends a package to all clients.
 /// </summary>
 /// <param name="package">The Package.</param>
 private void SendToAllClients(IBasePackage package)
 {
     for (int i = 0; i <= _connections.Count - 1; i++)
     {
         NetworkStream networkStream = _connections[i].Client.GetStream();
         PackageSerializer.Serialize(package, networkStream);
         //May not be neccessary
         networkStream.Flush();
     }
 }
Esempio n. 9
0
 /// <summary>
 /// Disconnect from the local server.
 /// </summary>
 public void Disconnect()
 {
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(new UdpPackage(UdpNotify.Bye), mStream);
         _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(_ip, 2563));
         _connected = false;
     }
     _udpClient.Close();
 }
Esempio n. 10
0
 /// <summary>
 /// Connects to the local server.
 /// </summary>
 /// <param name="ip">The Serverip.</param>
 public void Connect(IPAddress ip)
 {
     _ip = ip;
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(new UdpPackage(UdpNotify.Hi), mStream);
         _udpClient.Client.SendTo(mStream.ToArray(), new IPEndPoint(ip, 2563));
         _connected = true;
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Sends a NotificationPackage to all clients.
        /// </summary>
        /// <param name="mode">The Mode.</param>
        /// <param name="connections">The ConnectionParams.</param>
        private void SendNotificationPackage(NotificationMode mode, IConnection[] connections)
        {
            var notificationPackage = new NotificationPackage(connections, mode);

            for (int i = 0; i <= _connections.Count - 1; i++)
            {
                NetworkStream networkStream = _connections[i].Client.GetStream();
                PackageSerializer.Serialize(notificationPackage, networkStream);
                //May not be neccessary
                networkStream.Flush();
            }
        }
Esempio n. 12
0
 /// <summary>
 /// Sends a package to the given receivers.
 /// </summary>
 /// <param name="package">The Package.</param>
 public void Send(IBasePackage package)
 {
     byte[] result;
     using (var mStream = new MemoryStream())
     {
         PackageSerializer.Serialize(package, mStream);
         result = mStream.ToArray();
     }
     for (int i = 0; i <= _connections.Count - 1; i++)
     {
         _listener.Client.SendTo(result, new IPEndPoint(_connections[i].IPAddress, 2565));
     }
 }
Esempio n. 13
0
 /// <summary>
 /// Sends a package to the given receivers.
 /// </summary>
 /// <param name="package">The Package.</param>
 public void Send(IBasePackage package)
 {
     if (!_tcpClient.Connected)
     {
         throw new InvalidOperationException("The client is not connected.");
     }
     try
     {
         PackageSerializer.Serialize(package, _nStream);
         _nStream.Flush();
     }
     catch (Exception ex)
     {
         _logger.Error(ex.Message);
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Sending a ping request every 30 seconds to all clients.
        /// </summary>
        private void PingRequestLoop()
        {
            while (IsActive)
            {
                IConnection[] connectionList = SerializableConnection.FromIConnection(_connections.ToArray());
                //Send a ping request to all clients
                for (int i = 0; i <= _connections.Count - 1; i++)
                {
                    var pingPackage = new PingPackage {
                        Receiver = _connections[i].IPAddress
                    };
                    NetworkStream networkStream = _connections[i].Client.GetStream();
                    PackageSerializer.Serialize(pingPackage, networkStream);
                    //May not be neccessary
                    networkStream.Flush();

                    //Also update the client list.
                    SendNotificationPackage(NotificationMode.ClientList, connectionList);
                }
                //Idle for 15 seconds
                Thread.Sleep(15000);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Accepts clients if available.
        /// </summary>
        private void BeginAcceptConnections()
        {
            var incommingConnection = new IPEndPoint(IPAddress.Any, 2565);

            while (IsActive)
            {
                try
                {
                    if (_listener.Available > 0)
                    {
                        byte[] receivedData = _listener.Receive(ref incommingConnection);
                        using (var mStream = new MemoryStream(receivedData))
                        {
                            IBasePackage package    = PackageSerializer.Deserialize(mStream);
                            var          udpPackage = package as UdpPackage;
                            if (udpPackage != null)
                            {
                                if (udpPackage.NotifyMode == UdpNotify.Hi)
                                {
                                    //notify
                                    SendNotificationPackage(NotificationMode.ClientJoined, _connections.ToArray());
                                    //add connection
                                    var udpConnection = new UdpConnection(incommingConnection.Address);
                                    _connections.Add(udpConnection);
                                    // publish the new server list, after a new connection.
                                    SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray());
                                }
                                else //(UdpNotify.Bye)
                                {
                                    //notify
                                    SendNotificationPackage(NotificationMode.ClientExited, _connections.ToArray());
                                    //remove connection
                                    UdpConnection udpConnection = GetConnection(incommingConnection.Address);
                                    if (udpConnection != null)
                                    {
                                        _connections.Remove(udpConnection);
                                        // publish the new server list, after a lost connection.
                                        SendNotificationPackage(NotificationMode.ClientList, _connections.ToArray());
                                    }
                                }
                            }
                            else
                            {
                                //any other package handle in new void
                                HandlePackage(package);
                            }
                        }
                    }
                    else
                    {
                        //no data available

                        Idle();
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Starts receiving data.
        /// </summary>
        private void InternalBeginReceive()
        {
            while (_tcpClient.Connected)
            {
                try
                {
                    IBasePackage package = _tcpClient.Available > 0 ? PackageSerializer.Deserialize(_nStream) : null;
                    if (package == null)
                    {
                        //Idle the client.
                        Idle();
                        continue;
                    }
                    var binaryPackage = package as BinaryPackage;
                    if (binaryPackage != null)
                    {
                        //binary package
                        //Gets the subscriber list with the matching origin type
                        IEnumerable <IPackageListener> subscribers = GetPackageSubscriber(binaryPackage.OriginType);
                        foreach (IPackageListener subscriber in subscribers)
                        {
                            subscriber.OnPackageReceived(binaryPackage);
                        }

                        //Nothing more to do.
                        continue;
                    }
                    //determine, which package is it.
                    var notificationPackage = package as NotificationPackage;
                    if (notificationPackage != null)
                    {
                        //Notificationpackage

                        switch (notificationPackage.Mode)
                        {
                        //client joined
                        case NotificationMode.ClientJoined:
                            for (int i = 0; i <= _clientListeners.Count - 1; i++)
                            {
                                _clientListeners[i].OnClientJoined(notificationPackage.Connection[0]);
                            }
                            break;

                        //client exited
                        case NotificationMode.ClientExited:
                            for (int i = 0; i <= _clientListeners.Count - 1; i++)
                            {
                                _clientListeners[i].OnClientExited(notificationPackage.Connection[0]);
                            }
                            break;

                        //client listing
                        case NotificationMode.ClientList:
                            for (int i = 0; i <= _clientListeners.Count - 1; i++)
                            {
                                _clientListeners[i].OnClientListing(notificationPackage.Connection);
                            }
                            break;

                        //server shutdown
                        case NotificationMode.ServerShutdown:
                            for (int i = 0; i <= _clientListeners.Count - 1; i++)
                            {
                                _clientListeners[i].OnServerShutdown();
                                _tcpClient.Close();
                            }
                            break;

                        //we timed out.
                        case NotificationMode.TimeOut:
                            for (int i = 0; i <= _clientListeners.Count - 1; i++)
                            {
                                _clientListeners[i].OnClientTimedOut();
                            }
                            _tcpClient.Close();
                            break;
                        }

                        //exit sub
                        continue;
                    }
                    var pingPackage = package as PingPackage;
                    if (pingPackage != null)
                    {
                        //Pingpackage
                        //Send the ping package back to the server.
                        Send(pingPackage);
                        //exit sub
                        continue;
                    }

                    _logger.Error("Received unknown package.");
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message);
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Receives data.
        /// </summary>
        private void InternalBeginReceive()
        {
            while (_connected)
            {
                if (_udpClient.Available > 0)
                {
                    var    serverIpEndPoint = new IPEndPoint(IPAddress.Any, 2565);
                    byte[] receivedData     = _udpClient.Receive(ref serverIpEndPoint);
                    using (var mStream = new MemoryStream(receivedData))
                    {
                        IBasePackage package = PackageSerializer.Deserialize(mStream);

                        var binaryPackage = package as BinaryPackage;
                        if (binaryPackage != null)
                        {
                            //binary package
                            foreach (IPackageListener subscriber in GetPackageSubscriber(binaryPackage.OriginType))
                            {
                                subscriber.OnPackageReceived(binaryPackage);
                            }
                            continue;
                        }

                        //system packages
                        var systemPackage = package as NotificationPackage;
                        if (systemPackage != null)
                        {
                            switch (systemPackage.Mode)
                            {
                            case NotificationMode.ClientJoined:
                                for (int i = 0; i <= _clientListeners.Count - 1; i++)
                                {
                                    _clientListeners[i].OnClientJoined(systemPackage.Connection[0]);
                                }
                                break;

                            case NotificationMode.ClientExited:
                                for (int i = 0; i <= _clientListeners.Count - 1; i++)
                                {
                                    _clientListeners[i].OnClientExited(systemPackage.Connection[0]);
                                }
                                break;

                            case NotificationMode.ClientList:
                                for (int i = 0; i <= _clientListeners.Count - 1; i++)
                                {
                                    _clientListeners[i].OnClientListing(systemPackage.Connection);
                                }
                                break;

                            case NotificationMode.TimeOut:
                                for (int i = 0; i <= _clientListeners.Count - 1; i++)
                                {
                                    _clientListeners[i].OnClientTimedOut();
                                }
                                break;

                            case NotificationMode.ServerShutdown:
                                for (int i = 0; i <= _clientListeners.Count - 1; i++)
                                {
                                    _clientListeners[i].OnServerShutdown();
                                }
                                break;
                            }
                        }

                        var pingPackage = package as PingPackage;
                        if (pingPackage != null)
                        {
                            //send ping package back
                            Send(pingPackage);
                        }
                    }
                }
                else
                {
                    //no data available

                    Idle();
                }
            }
        }