/// <summary>
        /// A connection to our server, always listening asynchronously.
        /// </summary>
        /// <param name="socket">The Socket for the connection.</param>
        /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param>
        /// <param name="dataReceived">A callback invoked when data is recieved.</param>
        /// <param name="disconnectedCallback">A callback invoked on disconnection.</param>
        public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived,
            DisconnectedCallback disconnectedCallback)
        {
            logger = new ElibLogging("data");
            this.AuthorizationType = Securtiy.AuthorizationType.Anonymous;
            lock (this)
            {
                var remotIP = socket.RemoteEndPoint as IPEndPoint;
                var localIP = socket.LocalEndPoint as IPEndPoint;
                State state = new State()
                {
                    socket = socket,
                    dataReceived = dataReceived,
                    disconnectedCallback = disconnectedCallback,
                    Device = new Device()
                    {
                        RemoteIP = remotIP.Address.ToString(),
                        LocalIP = localIP.Address.ToString()
                    }
                };

                eventArgs = args;
                eventArgs.Completed += ReceivedCompleted;
                eventArgs.UserToken = state;

                ListenForData(eventArgs);
            }
        }
Beispiel #2
0
        private void ProcessDisconnectCallback(SocketAsyncEventArgs e)
        {
            SocketToken sToken = e.UserToken as SocketToken;

            if (sToken == null)
            {
                return;// throw new Exception("空异常");
            }

            try
            {
                sToken.Close();
                //递减信号量
                maxNumberAcceptedClients.Release();

                Interlocked.Decrement(ref numberOfConnections);
                if (sToken.TokenId != 0)
                {
                    //将断开的对象重新放回复用队列
                    acceptTokenManager.Set(e);
                }

                DisconnectedCallback?.Invoke(sToken);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #3
0
        public override bool Initialize()
        {
            if (IsInitialized)
            {
                return(IsInitialized);
            }

            try
            {
                if (RGBControl.IsConnected())
                {
                    IsInitialized = true;
                    _deviceInfo   = RGBControl.GetDeviceInfo().Model;
                    cb            = new DisconnectedCallback(OnDisconnect);
                    RGBControl.SetDisconnectedCallback(cb);
                }
                else
                {
                    IsInitialized = false;
                    _deviceInfo   = "";
                }
            }
            catch (Exception exc)
            {
                LogError("There was an error initializing Wooting SDK.\r\n" + exc.Message);

                IsInitialized = false;
            }

            return(IsInitialized);
        }
        /// <summary>
        /// A connection to our server, always listening asynchronously.
        /// </summary>
        /// <param name="socket">The Socket for the connection.</param>
        /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param>
        /// <param name="dataReceived">A callback invoked when data is recieved.</param>
        /// <param name="disconnectedCallback">A callback invoked on disconnection.</param>
        public ServerConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived,
                                DisconnectedCallback disconnectedCallback)
        {
            logger = new ElibLogging("data");
            this.AuthorizationType = Securtiy.AuthorizationType.Anonymous;
            lock (this)
            {
                var   remotIP = socket.RemoteEndPoint as IPEndPoint;
                var   localIP = socket.LocalEndPoint as IPEndPoint;
                State state   = new State()
                {
                    socket               = socket,
                    dataReceived         = dataReceived,
                    disconnectedCallback = disconnectedCallback,
                    Device               = new Device()
                    {
                        RemoteIP = remotIP.Address.ToString(),
                        LocalIP  = localIP.Address.ToString()
                    }
                };

                eventArgs            = args;
                eventArgs.Completed += ReceivedCompleted;
                eventArgs.UserToken  = state;

                ListenForData(eventArgs);
            }
        }
Beispiel #5
0
        /// <summary>
        /// 处理接收的数据
        /// </summary>
        /// <param name="e"></param>
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            try
            {
                if (stoped)
                {
                    if (e.ConnectSocket != null)
                    {
                        e.ConnectSocket.Close();
                    }
                    if (e.AcceptSocket != null)
                    {
                        e.AcceptSocket.Close();
                    }
                    acceptPool.Push(e);
                    return;
                }

                SocketToken sToken = e.UserToken as SocketToken;

                if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                {
                    ReceiveOffsetCallback?.Invoke(sToken, e.Buffer, e.Offset, e.BytesTransferred);

                    //处理接收到的数据
                    if (ReceivedCallback != null)
                    {
                        if (e.Offset == 0 && e.BytesTransferred == e.Buffer.Length)
                        {
                            ReceivedCallback(sToken, e.Buffer);
                        }
                        else
                        {
                            byte[] realBytes = new byte[e.BytesTransferred];
                            Buffer.BlockCopy(e.Buffer, e.Offset, realBytes, 0, e.BytesTransferred);
                            ReceivedCallback(sToken, realBytes);
                        }
                    }

                    //继续投递下一个接受请求
                    if (!sToken.TokenSocket.ReceiveAsync(e))
                    {
                        this.ProcessReceive(e);
                    }
                }
                else
                {
                    //关闭异常对象
                    CloseClientSocket(sToken);

                    DisconnectedCallback?.Invoke(sToken);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #6
0
        internal void Connect(int nPort, ConnectedCallback fOnConnected, MessageCallback fOnMessage, DisconnectedCallback fOnDisconnected)
        {
            _fOnConnected    = fOnConnected;
            _fOnMessage      = fOnMessage;
            _fOnDisconnected = fOnDisconnected;

            Log("Connecting...");

            Socket     newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep       = new IPEndPoint(IPAddress.Loopback, nPort);

            newSocket.BeginConnect(iep, new AsyncCallback(OnConnected), newSocket);
        }
Beispiel #7
0
        internal void Connect(ConnectedCallback fOnConnected, DisconnectedCallback fOnDisconnected)
        {
            _fOnConnected    = fOnConnected;
            _fOnDisconnected = fOnDisconnected;

            Log("Connecting...");

            Socket newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            int nPort = Controller.GetRegistryValue(Globals.Registry.Port, 23763);

            IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, nPort);

            newSocket.BeginConnect(iep, new AsyncCallback(OnConnected), newSocket);
        }
        /// <summary>
        /// 处理接收数据之后的事件
        /// </summary>
        /// <param name="e"></param>
        private void ProcessReceiveHandler(SocketAsyncEventArgs e)
        {
            try
            {
                if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
                {
                    ReceiveOffsetCallback?.Invoke(e.UserToken as SocketToken, e.Buffer, e.Offset, e.BytesTransferred);

                    if (RecievedCallback != null)
                    {
                        if (e.Offset == 0 && e.BytesTransferred == e.Buffer.Length)
                        {
                            RecievedCallback(e.UserToken as SocketToken, e.Buffer);
                        }
                        else
                        {
                            byte[] realBytes = new byte[e.BytesTransferred];

                            Buffer.BlockCopy(e.Buffer, e.Offset, realBytes, 0, e.BytesTransferred);
                            RecievedCallback(e.UserToken as SocketToken, realBytes);
                        }
                    }


                    if (!isConnected)
                    {
                        return;
                    }

                    if (!clientSocket.ReceiveAsync(e))
                    {
                        ProcessReceiveHandler(e);
                    }
                }
                else
                {
                    isConnected = false;

                    DisconnectedCallback?.Invoke(e.UserToken as SocketToken);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Disconnects from the assigned port.
        /// </summary>
        /// <exception cref="IOException">If disconnecting fails.</exception>
        override public void Disconnect()
        {
            if (!isConnected)
            {
                return;
            }

            isConnected = false;
            try
            {
                arduinoSerial.Close();
            }
            finally
            {
                DisconnectedCallback?.Invoke();
            }
        }
Beispiel #10
0
        private void CheckConnection()
        {
            runChecker       = true;
            refreshRequested = true;

            while (runChecker)
            {
                if (Monitor.TryEnter(arduinoConnection))
                {
                    try
                    {
                        if (!Send("1000"))
                        {
                            DisconnectedCallback?.Invoke();
                            TryConnect();
                            IsConnected = false;
                        }
                        else
                        {
                            ConnectedCallback?.Invoke();
                            IsConnected = true;
                        }
                    }
                    finally
                    {
                        if (Monitor.IsEntered(arduinoConnection))
                        {
                            Monitor.Exit(arduinoConnection);
                        }
                    }
                }

                int sleeptFor = 0;
                while (++sleeptFor < 2000)
                {
                    if (refreshRequested)
                    {
                        refreshRequested = false;
                        break;
                    }
                    Thread.Sleep(1);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// 处理断开连接
        /// </summary>
        /// <param name="e"></param>
        private void ProcessDisconnect(SocketAsyncEventArgs e)
        {
            try
            {
                Interlocked.Decrement(ref numberOfConnections);

                //递减信号量
                acceptSemphoreClients.Release();

                //将断开的对象重新放回复用队列
                acceptPool.Push(e);

                DisconnectedCallback?.Invoke(e.UserToken as SocketToken);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// A connection to our server, always listening asynchronously.
        /// </summary>
        /// <param name="socket">The Socket for the connection.</param>
        /// <param name="args">The SocketAsyncEventArgs for asyncronous recieves.</param>
        /// <param name="dataReceived">A callback invoked when data is recieved.</param>
        /// <param name="disconnectedCallback">A callback invoked on disconnection.</param>
        public NetConnection(Socket socket, SocketAsyncEventArgs args, DataReceivedCallback dataReceived,
                             DisconnectedCallback disconnectedCallback, T session)
        {
            lock (this)
            {
                this.packageHandler = new PackageHandler <NetConnection <T> >(this);
                State state = new State()
                {
                    socket               = socket,
                    dataReceived         = dataReceived,
                    disconnectedCallback = disconnectedCallback
                };
                eventArgs = new SocketAsyncEventArgs();
                eventArgs.AcceptSocket = socket;
                eventArgs.Completed   += ReceivedCompleted;
                eventArgs.UserToken    = state;
                eventArgs.SetBuffer(new byte[64 * 1024], 0, 64 * 1024);

                BeginReceive(eventArgs);
                this.session = session;
            }
        }
 /// <summary>
 /// Fires the DisconnectedCallback.
 /// </summary>
 /// <param name="args">The SocketAsyncEventArgs for this connection.</param>
 /// <param name="callback">The callback.</param>
 private void OnDisconnected(SocketAsyncEventArgs args, DisconnectedCallback callback)
 {
     callback(this, args);
 }
 /// <summary>
 /// Fires the DisconnectedCallback.
 /// </summary>
 /// <param name="args">The SocketAsyncEventArgs for this connection.</param>
 /// <param name="callback">The callback.</param>
 private void OnDisconnected(SocketAsyncEventArgs args, DisconnectedCallback callback)
 {
     callback(this, args);
 }
Beispiel #15
0
 public static extern void SetDisconnectedCallback(DisconnectedCallback cb);