Exemple #1
0
        /// <summary>
        /// Stops listening to the specified end point. Does not close any connections.
        /// </summary>
        /// <param name="endPoint">The end point</param>
        public override void StopListening(object endPoint)
        {
            lock (this)
            {
                if (this._socket == null)
                {
                    return;
                }

                // LOG:
                BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.Connection] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.Connection, "UdpConnectionManager.StopListening",
                                               LogMessageType.ListeningStopped, null, null, null, null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, this.DbgConnectionId, 0, 0, 0, null, null, null, null,
                                               "The listening socket is not longer associated with the {0} local end point.", endPoint == null ? string.Empty : endPoint.ToString());
                }

                SocketUtility.CloseSocket(this._socket);
                this._socket = null;

                this._closing = true;
            }

            if (!this._receivingThreadClosed.WaitOne(TimeSpan.FromMinutes(2), false))
            {
                throw GenuineExceptions.Get_Processing_LogicError("Receiving thread didn't exit within 2 minutes.");
            }
        }
        private void _ResolveHostAddress
        (
            string host
        )
        {
            Sure.NotNullNorEmpty(host, nameof(host));

            if (ReferenceEquals(_address, null))
            {
                _address = SocketUtility.ResolveAddressIPv4(host);
                if (_address.AddressFamily != AddressFamily.InterNetwork)
                {
                    throw new IrbisNetworkException
                          (
                              "Address must be IPv4 only!"
                          );
                }
            }

            //if (ReferenceEquals(_address, null))
            //{
            //    throw new IrbisNetworkException
            //        (
            //            "Can't resolve host " + host
            //        );
            //}
        }
        public SocketClientManager()
        {
            InitializeComponent();

            _SocketViewModel = new SocketViewModel();
            BindingContext   = _SocketViewModel;

            _SocketClient = new SocketClient();
            _Data         = SocketUtility.GetRandomData(1000);

            _Device = DependencyService.Get <IDevicePh>();
        }
Exemple #4
0
 public SocketClient(string ip, int port)
 {
     try
     {
         tcpSocket = new TcpClient(ip, port);
         Task.Factory.StartNew(new Action(() =>
         {
             SocketUtility.SocketStreamReceive(tcpSocket, MessageReceiveHandler);
         }));
     }
     catch (Exception e)
     {
         OnExceptionReceive?.Invoke(e.Message);
     }
 }
        private void manageMiddlewareRead()
        {
            var stream = _middleware.GetStream();

            try
            {
                OnMiddlewareConnected?.Invoke("Connected to Middleware");
                SocketUtility.SocketStreamReceive(_middleware, HandleMessage);
            }
            catch (Exception e)
            {
                OnExceptionReceive?.Invoke(e.Message);
                OnMiddlewareConnected?.Invoke("Discnnected from Middleware");
            }
            _listener.BeginAcceptTcpClient(beginAcceptTcpClient, null);
        }
Exemple #6
0
        private void beginAcceptTcpClient(IAsyncResult ar)
        {
            TcpClient client = serverListener.EndAcceptTcpClient(ar);

            clientListener.BeginAcceptTcpClient(beginAcceptTcpClient, null);
            clients.Add(client);
            OnClientConnected?.Invoke(client.Client.RemoteEndPoint.AddressFamily.ToString());
            try
            {
                SocketUtility.SocketStreamReceive(client, ClientHandleMessage);
            }
            catch (Exception e)
            {
                OnExceptionReceive?.Invoke(e.Message);
                OnClientDisconnected?.Invoke(client.Client.RemoteEndPoint.AddressFamily.ToString());
                clients.Remove(client);
            }
        }
Exemple #7
0
        private void _ResolveHostAddress
        (
            string host
        )
        {
            Sure.NotNullNorEmpty(host, nameof(host));

            if (ReferenceEquals(_address, null))
            {
                _address = SocketUtility.ResolveAddressIPv4(host);
            }

            if (ReferenceEquals(_address, null))
            {
                throw new IrbisNetworkException
                      (
                          "Can't resolve host " + host
                      );
            }
        }
Exemple #8
0
        private void beginAcceptTcpServer(IAsyncResult ar)
        {
            TcpClient server = serverListener.EndAcceptTcpClient(ar);

            serverListener.BeginAcceptTcpClient(beginAcceptTcpServer, null);

            servers.Add(server);
            OnServerConnected?.Invoke(server.Client.RemoteEndPoint.AddressFamily.ToString());

            try
            {
                SocketUtility.SocketStreamReceive(server, ServerHandleMessage);
            }
            catch (Exception e)
            {
                OnExceptionReceive?.Invoke(e.Message);
                OnServerDisconnected?.Invoke(server.Client.RemoteEndPoint.AddressFamily.ToString());
                servers.Remove(server);
            }
        }
Exemple #9
0
        /// <summary>
        /// ClientHandleMessage is invoked when a Client has sent a message to the middle ware, you need to forward it to the according server
        /// the data part should contain a target server it'll tell for which the message is intended for.
        /// </summary>
        /// <param name="model"></param>
        private void ClientHandleMessage(MessageModel model)
        {
            switch (model.MessageType)
            {
            case MessageType.CreatePlayList:
                //TODO: Create a PlayListModel and Receive it from the Client, then forward it to the according server.
                //E.G MessageModel { Data = YourPlayListModel } the Data is a Object Type so your data can be boxed inside it
                //On each Receivers end you will have to unbox it. e.g  YourPlayList yourPlayList = model.Data as YourPlayList;
                // See ServerListModel and set the Target as per your need. e.g from the Form the selected server will be the target,
                break;

            case MessageType.UploadPlayList:
                break;

            case MessageType.UploadFile:
                break;

            case MessageType.PlayRandomVideo:
                break;

            case MessageType.Query:
                break;

            case MessageType.MiddlewareCommand:
                break;

            case MessageType.ServerList:
                var d = model.Data as ServerListModel;
                d.ClientIPs.AddRange(servers.Select(t => t.Client.AddressFamily.ToString()).ToArray());
                SocketUtility.SocketStreamSend(clients.FirstOrDefault(t => t.Client.AddressFamily.ToString() == d.connection.Target), model);
                break;

            default:
                break;
            }
        }
Exemple #10
0
 public void MessageSend(MessageModel model)
 {
     //UpdateCommand;
     SocketUtility.SocketStreamSend(tcpSocket, model);
 }
        /// <summary>
        /// Select on NetMQSocket or Socket, similar behavior to Socket.Select.
        /// </summary>
        /// <param name="items">Items to select on (must not be null)</param>
        /// <param name="itemsCount">Number of items in the array to select on</param>
        /// <param name="timeout">a time-out period, in milliseconds</param>
        /// <returns></returns>
        /// <exception cref="FaultException">The internal select operation failed.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="items"/> is <c>null</c>.</exception>
        /// <exception cref="TerminatingException">The socket has been stopped.</exception>
        public bool Select([NotNull] Item[] items, int itemsCount, long timeout)
        {
            if (items == null)
            {
                throw new ArgumentNullException(nameof(items));
            }

            if (itemsCount == 0)
            {
                return(false);
            }

            bool firstPass      = true;
            int  numberOfEvents = 0;

            Stopwatch stopwatch = null;

            while (true)
            {
                long currentTimeoutMicroSeconds;

                if (firstPass)
                {
                    currentTimeoutMicroSeconds = 0;
                }
                else if (timeout < 0)
                {
                    // Consider everything below 0 to be infinite
                    currentTimeoutMicroSeconds = -1;
                }
                else
                {
                    currentTimeoutMicroSeconds = (timeout - stopwatch.ElapsedMilliseconds) * 1000;

                    if (currentTimeoutMicroSeconds < 0)
                    {
                        currentTimeoutMicroSeconds = 0;
                    }
                    else if (currentTimeoutMicroSeconds > int.MaxValue)
                    {
                        currentTimeoutMicroSeconds = int.MaxValue;
                    }
                }

                m_checkRead.Clear();
                m_checkWrite.Clear();
                m_checkError.Clear();

                for (int i = 0; i < itemsCount; i++)
                {
                    var pollItem = items[i];

                    if (pollItem.Socket != null)
                    {
                        if (pollItem.Event != PollEvents.None && pollItem.Socket.SocketHandle.Handle.Connected)
                        {
                            m_checkRead.Add(pollItem.Socket.SocketHandle.Handle);
                        }
                    }
                    else
                    {
                        if (pollItem.Event.HasIn())
                        {
                            m_checkRead.Add(pollItem.FileDescriptor);
                        }

                        if (pollItem.Event.HasOut())
                        {
                            m_checkWrite.Add(pollItem.FileDescriptor);
                        }
                    }
                }

                try
                {
                    SocketUtility.Select(m_checkRead, m_checkWrite, m_checkError, (int)currentTimeoutMicroSeconds);
                }
                catch (SocketException x)
                {
#if DEBUG
                    string textOfListRead  = StringLib.AsString(m_checkRead);
                    string textOfListWrite = StringLib.AsString(m_checkWrite);
                    string textOfListError = StringLib.AsString(m_checkError);
                    string xMsg            = $"In Selector.Select, Socket.Select({textOfListRead}, {textOfListWrite}, {textOfListError}, {currentTimeoutMicroSeconds}) threw a SocketException: {x.Message}";
                    Debug.WriteLine(xMsg);
                    throw new FaultException(innerException: x, message: xMsg);
#else
                    throw new FaultException(innerException: x, message: "Within SocketUtility.Select");
#endif
                }

                for (int i = 0; i < itemsCount; i++)
                {
                    var selectItem = items[i];

                    selectItem.ResultEvent = PollEvents.None;

                    if (selectItem.Socket != null)
                    {
                        var events = (PollEvents)selectItem.Socket.GetSocketOption(ZmqSocketOption.Events);

                        if (selectItem.Event.HasIn() && events.HasIn())
                        {
                            selectItem.ResultEvent |= PollEvents.PollIn;
                        }

                        if (selectItem.Event.HasOut() && events.HasOut())
                        {
                            selectItem.ResultEvent |= PollEvents.PollOut;
                        }
                    }
                    else
                    {
                        if (m_checkRead.Contains(selectItem.FileDescriptor))
                        {
                            selectItem.ResultEvent |= PollEvents.PollIn;
                        }

                        if (m_checkWrite.Contains(selectItem.FileDescriptor))
                        {
                            selectItem.ResultEvent |= PollEvents.PollOut;
                        }
                    }

                    if (selectItem.ResultEvent != PollEvents.None)
                    {
                        numberOfEvents++;
                    }
                }

                if (timeout == 0)
                {
                    break;
                }

                if (numberOfEvents > 0)
                {
                    break;
                }

                if (timeout < 0)
                {
                    if (firstPass)
                    {
                        firstPass = false;
                    }

                    continue;
                }

                if (firstPass)
                {
                    stopwatch = Stopwatch.StartNew();
                    firstPass = false;
                    continue;
                }

                // Check also equality as it might frequently occur on 1000Hz clock
                if (stopwatch.ElapsedMilliseconds >= timeout)
                {
                    break;
                }
            }

            return(numberOfEvents > 0);
        }
Exemple #12
0
        /// <summary>
        /// Connect to the server.
        /// </summary>
        /// <param name="retryInBackground">If false, the client will not retry to connect if the connection fails.</param>
        /// <returns></returns>
        public bool Connect(string hostName, int port, bool retryInBackground)
        {
            IPAddress ipAddress = SocketUtility.GetIPv4Address(hostName);

            return(Connect(ipAddress, port, retryInBackground));
        }
        /// <summary>
        /// Accepts incoming connections.
        /// </summary>
        public void AcceptConnections()
        {
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;
            Exception       exception       = null;
            int             numberOfFailure = 0;

            try
            {
                for ( ; ;)
                {
                    try
                    {
                        if (this.IAcceptConnectionConsumer.IsDisposed())
                        {
                            return;
                        }
                        if (this.StopListening.WaitOne(0, false))
                        {
                            return;
                        }

                        Socket clientSocket = this.Socket.Accept();
                        GenuineThreadPool.QueueUserWorkItem(new WaitCallback(this.AcceptConnection), clientSocket, true);
                    }
                    catch (Exception ex)
                    {
                        numberOfFailure++;

                        // LOG:
                        if (binaryLogWriter != null && binaryLogWriter[LogCategory.AcceptingConnection] > 0)
                        {
                            binaryLogWriter.WriteEvent(LogCategory.AcceptingConnection, "GenuineTcp.AcceptConnectionClosure.AcceptConnections",
                                                       LogMessageType.ConnectionAccepting, ex, null, null, null,
                                                       GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                                       null, null, -1, 0, 0, 0, null, null, null, null,
                                                       "An inbound TCP connection has not been accepted. Number of failure: {0}.", numberOfFailure);
                        }

                        this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GeneralListenerFailure, ex, null, ListeningEndPoint));
                    }
                }
            }
            catch (Exception ex)
            {
                exception = ex;

                // LOG:
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.AcceptingConnection] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.AcceptingConnection, "GenuineTcp.AcceptConnectionClosure.AcceptConnections",
                                               LogMessageType.ListeningStopped, ex, null, null, null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1, 0, 0, 0, null, null, null, null,
                                               "Fatal Error. The socket does not accept inbound connections any longer.");
                }

                this.ITransportContext.IGenuineEventProvider.Fire(new GenuineEventArgs(GenuineEventType.GeneralListenerFailure, ex, null, this.ListeningEndPoint));
            }
            finally
            {
                SocketUtility.CloseSocket(this.Socket);
            }
        }
Exemple #14
0
        public void StartClient(string serverIp, int serverPort, byte[] data)
        {
            try
            {
                _Timer = new Stopwatch();
                _Timer.Stop();

                _ConnectDone = new ManualResetEvent(false);
                _SendDone    = new ManualResetEvent(false);
                _ReceiveDone = new ManualResetEvent(false);

                // Get client
                IPAddress ipa    = IPAddress.Parse(SocketUtility.GetLocalIpAddress());
                Socket    client = new Socket(ipa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                // Get server
                IPAddress  serverIpa = IPAddress.Parse(serverIp);
                IPEndPoint serverIpe = new IPEndPoint(serverIpa, serverPort);

                LOG("Starting connection to " + serverIpa.ToString() + ":" + serverPort);

                // Begin connection
                client.BeginConnect(serverIpe, new AsyncCallback(ConnectionCallback), client);
                _ConnectDone.WaitOne();

                LOG("Start sending " + data.Length + " bytes for " + LOOP_ITERS + " loops");
                _Timer.Restart();

                // Sending data
                int i = LOOP_ITERS;
                while (i > 0)
                {
                    client.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), client);
                    _SendDone.WaitOne();
                    i--;
                }
                var eof = SocketUtility.GetEncoding.GetBytes(SocketUtility.DEF_EOF);
                client.BeginSend(eof, 0, eof.Length, SocketFlags.None, new AsyncCallback(SendCallback), client);
                _SendDone.WaitOne();

                LOG("End sending data, t=" + _Timer.ElapsedMilliseconds + "[ms]");
                LOG("Begin receiving the answer");
                _Timer.Stop();

                // Begin receive data
                SocketState state = new SocketState {
                    Instance = client
                };
                client.BeginReceive(state.Buffer, 0, SocketState.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
                _ReceiveDone.WaitOne();

                // Close client socket
                client.Shutdown(SocketShutdown.Both);
                client.Close();

                LOG("Closing the client");
            }
            catch (Exception ex)
            {
                LOG_ERR("start client error", ex);
            }
        }
 public void SendToMiddleware(MessageModel model)
 {
     SocketUtility.SocketStreamSend(_middleware, model);
 }
Exemple #16
0
 public void SendClient(MessageModel model, int ClientIndex)
 {
     SocketUtility.SocketStreamSend(clients[ClientIndex], model);
 }
Exemple #17
0
 public void SendServer(MessageModel model, int ServerIndex)
 {
     SocketUtility.SocketStreamSend(servers[ServerIndex], model);
 }