예제 #1
0
        //Reads incoming data from client, based on length of data we got earlier
        //Keeps reading until it gets exact amount of bytes we need
        private void ReceiveMessage(int size)
        {
            try
            {
                int total = 0;

                byte[] buffer = new byte[size];
                do
                {
                    IAsyncResult result = ClientReader.BeginReceive(buffer, total, size, SocketFlags.None, null, null);
                    result.AsyncWaitHandle.WaitOne(ClientReader.ReceiveTimeout);
                    int received = ClientReader.EndReceive(result);
                    total += received;
                    if (received == 0)
                    {
                        break;
                    }
                } while (total < size);
                OnReceived?.Invoke(buffer, size);
            }
            catch
            {
                OnDisconnected?.Invoke(ClientReader);
            }
        }
 public ChunkRequest(Vector3 worldPos, float voxelSize, OnReceived callback, LastCheck lastCheck)
 {
     this.worldPos  = worldPos;
     this.voxelSize = voxelSize;
     this.callback  = callback;
     this.lastCheck = lastCheck;
 }
예제 #3
0
        protected virtual void OnSend(RXSendMessage sendMsg)
        {
            var maybeReadRequest           = AttributeReadRequest.DecodeFromByteArray(sendMsg.Bytes);
            AttributeReadResult readResult = new AttributeReadResult
            {
                ReadState = AttributeReadState.Error
            };

            if (Attributes.ContainsKey(maybeReadRequest.RequestKey))
            {
                var value = Attributes[maybeReadRequest.RequestKey];
                readResult = new AttributeReadResult
                {
                    RequestGuid = maybeReadRequest.RequestGuid,
                    ReadState   = AttributeReadState.Successful,
                    Value       = value
                };
            }
            else
            {
                readResult = new AttributeReadResult
                {
                    RequestGuid = maybeReadRequest.RequestGuid,
                    ReadState   = AttributeReadState.NonExsited
                };
            }
            RXReceiveMessage receiveMessage = new RXReceiveMessage
            {
                RXConnection = this,
                Bytes        = readResult.EncodeToBytesArray()
            };

            OnReceived?.Invoke(this, receiveMessage);
        }
예제 #4
0
 public bool Connect(IPEndPoint endPoint)
 {
     if (!active)
     {
         try
         {
             this.client = new TcpClient();
             this.client.Connect(endPoint);
             NetworkStream networkStream = this.client.GetStream();
             this.networkConnection = new NetworkConnection(ref networkStream, (IPEndPoint)client.Client.RemoteEndPoint);
             this.networkConnection.OnSuccessfulConnection += (x, y) => OnClientConnected?.Invoke(x, y);
             this.networkConnection.OnError        += (x, y) => OnError?.Invoke(x, y);
             this.networkConnection.OnReceived     += (x, y) => OnReceived?.Invoke(x, y);
             this.networkConnection.OnDisconnected += (x, y) => OnClientDisconnected?.Invoke(x, y);
             this.active = true;
         }
         catch (Exception e)
         {
             OnError?.Invoke(networkConnection, e);
         }
         finally
         {
             if (!active)
             {
                 this.networkConnection?.Shutdown();
                 this.client?.Close();
                 this.networkConnection = null;
                 this.client            = null;
             }
         }
     }
     return(active);
 }
예제 #5
0
 public void OnDataReceive(string msg)
 {
     if (OnReceived != null)
     {
         OnReceived.Invoke(msg);
     }
 }
    public static void Enqueue(Vector3 worldPos, float voxelSize, OnReceived callback, LastCheck lastCheck, float priority, int id = -1)
    {
        ChunkRequest cr = new ChunkRequest(worldPos, voxelSize, callback, lastCheck);

        cr.id = id;
        queue.Enqueue(cr, priority);
    }
 private Task _ReadInputStreamTaskAsync()
 {
     return(Task.Run(() =>
     {
         var inputStream = RfcommConnection.InputStream;
         bool disconnected = false;
         while (true)
         {
             byte[] buffer = new byte[255];
             var readSize = inputStream.Read(buffer, 0, buffer.Length);
             if (readSize == 0)
             {
                 disconnected = true;
                 break;
             }
             var readBytes = new byte[readSize];
             Array.Copy(buffer, 0, readBytes, 0, readSize);
             var msg = new RXReceiveMessage
             {
                 RXConnection = this,
                 Bytes = readBytes
             };
             OnReceived?.Invoke(this, msg);
         }
         if (disconnected)
         {
             RfcommConnection.Dispose();
             ConnectionState = RXConnectionState.Destoryed;
             OnConnectionStateChanged?.Invoke(this, ConnectionState);
         }
     }));
 }
예제 #8
0
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="clientSocket"></param>
        private void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;

            while (true)
            {
                try
                {
                    //通过clientSocket接收数据
                    int receiveNumber = myClientSocket.Receive(result);
                    OnReceived?.Invoke(this, new ReceiveMessageData()
                    {
                        Message = Encoding.ASCII.GetString(result, 0, receiveNumber)
                    });
                    //Console.WriteLine("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                }
                catch (Exception ex)
                {
                    //Log.OutputBox(ex);
                    //Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }
 private void ReadCallbackUDP(IAsyncResult ar)
 {
     try
     {
         if (!Socket.Connected)
         {
             return;
         }
         int readBytes = Socket.EndReceive(ar);
         if (readBytes > 0)
         {
             byte[] data = new byte[readBytes];
             Array.Copy(Buffer, data, readBytes);
             OnReceived?.Invoke(this, new SocketClientEventArgs()
             {
                 Data = data
             });
         }
         Socket.BeginReceive(Buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallbackUDP), null);
     }
     catch (SocketException se)
     {
         OnError?.Invoke(this, new ErrorEventArgs(se));
     }
 }
예제 #10
0
        public void ReadCallback(IAsyncResult ar)
        {
            log.add_to_log(log_vrste.info, "EndRead", "AsyncTCPClient.cs ReadCallback()");
            Connection connection = (Connection)ar.AsyncState;

            int            bytesRead = connection.socket.EndReceive(ar);
            IOStatus       status;
            List <Message> messages = io.EndRead(connection, bytesRead, out status);

            if (messages.Count > 0)
            {
                /*connection.socket.BeginReceive(connection.bytes_read, 0, Connection.RBUFFER_SIZE, SocketFlags.None,
                 *      new AsyncCallback(ReadCallback), connection);*/

                /*if (status == IOStatus.INCOMPLETE)
                 * {
                 *  connection.socket.BeginReceive(connection.bytes_read, 0, Connection.RBUFFER_SIZE, SocketFlags.None,
                 *      new AsyncCallback(ReadCallback), connection);
                 * }*/
                ReceivedEventArgs args = new ReceivedEventArgs(connection.uid, messages.ToArray());
                OnReceived?.Invoke(this, args);
            }
            //
            //{
            log.add_to_log(log_vrste.info, "BeginReceive", "AsyncTCPClient.cs ReadCallback()");
            connection.socket.BeginReceive(connection.tmp_rbuffer, 0, Connection.RBUFFER_SIZE, SocketFlags.None,
                                           new AsyncCallback(ReadCallback), connection);
            //}
        }
예제 #11
0
        private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs)
        {
            if (eventArgs.SocketError != SocketError.Success)
            {
                Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}");
            }

            OnConnected?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs);

            if (eventArgs.BytesTransferred == 0)
            {
                OnClosed?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs);
                eventArgs.Dispose();
                return;
            }

            (var transport, var transportMessage) = ((UdpHostTransport, TransportMessage))eventArgs.UserToken;

            transportMessage.UpdateBytesReceived();

            // For now, UDP messages cannot extend across a single message
            OnReceived?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, transportMessage);
            transportMessage.Reset(UdpPacketSize);

            _autoResetEvent.Set();
        }
예제 #12
0
        public void Receive(Message message)
        {
            _history.Add(message);

            // YOUR CODE GOES HERE
            OnReceived?.Invoke(message);
        }
예제 #13
0
        private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs)
        {
            if (eventArgs.SocketError != SocketError.Success)
            {
                Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}");
            }

            (var transport, var transportMessage) = ((TcpClientTransport, TransportMessage))eventArgs.UserToken;

            if (eventArgs.BytesTransferred == 0)
            {
                OnClosed?.Invoke(ProtocolType.Tcp, _remoteEndPoint, eventArgs);
                eventArgs.Dispose();
                return;
            }

            transportMessage.UpdateBytesReceived();

            // Check if we're done
            if (transportMessage.IsReady)
            {
                OnReceived?.Invoke(ProtocolType.Tcp, _remoteEndPoint, transportMessage);
                transportMessage.Reset();
            }

            StartReceivingAsync(eventArgs);
        }
 private void ReceivedEvent(string data)
 {
     if (OnReceived == null)
     {
         return;
     }
     OnReceived.Invoke(data);
 }
 internal override void DataProcessingCenter(AppSession session, int protocol, int customer, byte[] content)
 {
     if (protocol == InsideProtocol.ProtocolUserString)
     {
         action?.Invoke(this, Encoding.Unicode.GetString(content));
         OnReceived?.Invoke(this, Encoding.Unicode.GetString(content));
     }
 }
예제 #16
0
 private async Task ReadCallback()
 {
     while (ContinueReading)
     {
         var received = cryptographicFunction.Decrypt(await Read().ConfigureAwait(false), Key);
         OnReceived?.Invoke(JsonSerializer.Deserialize <BaseMessage>(received));
     }
 }
예제 #17
0
        private void Run()
        {
            while (alive)
            {
                try
                {
                    lock (clientList)
                    {
                        int index = 0;
                        while (index < clientList.Count)
                        {
                            if (!IsConnected(clientList[index]))
                            {
                                if (OnDisconnected != null)
                                {
                                    OnDisconnected.Invoke(clientList[index].Client.LocalEndPoint, clientList[index].Client.RemoteEndPoint);
                                }
                                clientList.RemoveAt(index);
                            }
                            else
                            {
                                index++;
                            }
                        }

                        foreach (TcpClient client in clientList)
                        {
                            NetworkStream stream = client.GetStream();
                            if (stream != null)
                            {
                                byte[][] commands = ReceiveBytes(stream);
                                if (OnReceived != null)
                                {
                                    foreach (byte[] command in commands)
                                    {
                                        byte[] response = OnReceived.Invoke(command);
                                        if (response != null && response.Length > 0)
                                        {
                                            SendBytes(stream, response, terminator);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    Console.WriteLine(ex);
#endif
                }
                finally
                {
                    Thread.Sleep(interval);
                }
            }
        }
예제 #18
0
        /// <summary>
        ///     Will fire all events according to the queued messages
        /// </summary>
        public void Work()
        {
            if (Stopped)
            {
                throw new InvalidOperationException($"{nameof(EasySocket)} was stopped");
            }
            SocketAsyncEventArgs result;

            while (!_acceptedSockets.IsEmpty)
            {
                if (_acceptedSockets.TryDequeue(out result))
                {
                    OnAccepted?.Invoke(Socket, result);
                }
            }

            while (!_receivedData.IsEmpty)
            {
                if (_receivedData.TryDequeue(out result))
                {
                    OnReceived?.Invoke(Socket, result);
                }
            }

            while (!_receivedFromData.IsEmpty)
            {
                if (_receivedFromData.TryDequeue(out result))
                {
                    OnReceivedFrom?.Invoke(Socket, result);
                }
            }

            while (!_receivedMessageFromData.IsEmpty)
            {
                if (_receivedMessageFromData.TryDequeue(out result))
                {
                    OnReceivedMessageFrom?.Invoke(Socket, result);
                }
            }

            while (!_sendComplete.IsEmpty)
            {
                if (_sendComplete.TryDequeue(out result))
                {
                    OnSent?.Invoke(Socket, result);
                }
            }

            while (!_sendToComplete.IsEmpty)
            {
                if (_sendToComplete.TryDequeue(out result))
                {
                    OnSentTo?.Invoke(Socket, result);
                }
            }
        }
예제 #19
0
 public TransportManager(IEnumerable <IClientTransport> transports)
 {
     foreach (var transport in transports)
     {
         _transports[transport.ProtocolType] = transport;
         transport.OnConnected += (p, e, saea) => (OnConnected?.Invoke(p, e, saea) ?? Task.CompletedTask);
         transport.OnReceived  += (p, e, m) => (OnReceived?.Invoke(p, e, m) ?? Task.CompletedTask);
         transport.OnClosed    += (p, e, saea) => (OnClosed?.Invoke(p, e, saea) ?? Task.CompletedTask);
     }
 }
예제 #20
0
 void DataReceived(SDDataReceivedEventArgs args)
 {
     OnReceived?.Invoke(args);
     if (lastSent < Time.time)
     {
         OnProgress?.Invoke(args);
         lastSent = Time.time + 0.1f;
         CalculateAvrage();
     }
 }
예제 #21
0
 void StartReceive()
 {
     try
     {
         int           bufLen = 1024;
         byte[]        buffer = new byte[bufLen];
         NetworkStream stream = _client.GetStream();
         while (_isRunning && !_disposing)
         {
             //while (stream.DataAvailable)
             //{
             int readBytes = stream.Read(buffer, 0, bufLen);
             if (readBytes > 0)
             {
                 //string msg = Encoding.UTF8.GetString(buffer, 0, readBytes);
                 string msg = Encoding.GetEncoding("gbk").GetString(buffer, 0, readBytes);
                 OnReceived?.Invoke(this, msg);
             }
             else
             {
                 FireClosed();
             }
             //}
             Thread.Sleep(5);
         }
     }
     catch (IOException) { FireClosed(); }
     catch (ArgumentOutOfRangeException)
     {
         if (!_disposing)
         {
             LogHelper.Write("LXTcpConnection", "ArgumentOutOfRangeException");
         }
     }
     catch (ObjectDisposedException)
     {
         if (!_disposing)
         {
             LogHelper.Write("LXTcpConnection", "ObjectDisposedException");
         }
         FireClosed();
     }
     catch (InvalidOperationException)
     {
         if (!_disposing)
         {
             LogHelper.Write("LXTcpConnection", "InvalidOperationException");
         }
         FireClosed();
     }
     catch (Exception ex)
     {
         LogHelper.Write("LXTcpConnection", ex);
     }
 }
예제 #22
0
 private void RaiseOnReceive(DataReceivedArgs args)
 {
     try
     {
         //var data = args.Data;
         OnReceived?.Invoke(args);
     }
     catch (Exception)
     {
     }
 }
예제 #23
0
        public Task <OperateResult> SendAsync(TransportMessage message)
        {
            var typeName = message.Headers["DotNetType"];
            var streamId = message.Headers["StreamId"];
            var type     = Type.GetType(typeName);
            var json     = Encoding.UTF8.GetString(message.Body);
            var evt      = JsonConvert.DeserializeObject(json, type);

            OnReceived?.Invoke(new CapMessage(streamId, evt));
            return(Task.FromResult(OperateResult.Success));
        }
예제 #24
0
        /// <summary>
        /// WebSocket監聽主程序
        /// </summary>
        /// <param name="context">Http通訊內容</param>
        /// <param name="socket">WebSocket物件</param>
        protected async Task Listen(HttpContext context, WebSocket socket)
        {
            OnConnected?.Invoke(context, socket);
            Exception exception = null;

            //監聽迴圈
            while (socket.State == WebSocketState.Open)
            {
                List <byte>            receiveData   = new List <byte>();
                WebSocketReceiveResult receiveResult = null;

                //分段存取迴圈
                do
                {
                    //緩衝區
                    ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[BufferSize]);

                    try {
                        //接收資料
                        receiveResult = await socket.ReceiveAsync(buffer, CancellationToken.None);
                    } catch (Exception e) {
                        exception = e;
                        break;
                    }
                    byte[] rawData = buffer.Array.Take(receiveResult.Count).ToArray();

                    OnReceiving?.Invoke(
                        socket,
                        receiveResult.MessageType,
                        rawData,
                        receiveResult.EndOfMessage);

                    receiveData.AddRange(rawData);
                } while (!receiveResult.EndOfMessage);

                OnReceived?.Invoke(socket, receiveResult.MessageType, receiveData.ToArray());

                //檢查是否關閉連線,如關閉則跳脫循環監聽
                if (exception != null ||
                    receiveResult.CloseStatus.HasValue ||
                    socket.State != WebSocketState.Open)
                {
                    break;
                }
            }

            if (exception != null)
            {
                OnException?.Invoke(socket, exception);
            }

            OnDisconnected?.Invoke(context, socket);
        }
예제 #25
0
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] data = new byte[serialPort.BytesToRead];
            serialPort.Read(data, 0, data.Length);

            // Encoding enc = Encoding.GetEncoding(1251);
            //String buffer = enc.GetString(data);

            OnReceivedEventArgs args = new OnReceivedEventArgs(data);

            OnReceived.Invoke(this, args);
        }
예제 #26
0
        private void _server_OnReceive(object userToken, byte[] data)
        {
            var ut = (IUserToken)userToken;

            var up = (MyUnpacker)ut.Unpacker;

            up.Unpack(data, (package) =>
            {
                OnReceived?.Invoke(package);

                _server.SendAsync(ut.ID, up.Process(package));
            });
        }
예제 #27
0
        private void doChat()
        {
            NetworkStream stream = null;

            try
            {
                byte[] buffer       = new byte[1024];
                string msg          = string.Empty;
                int    bytes        = 0;
                int    MessageCount = 0;

                while (true)
                {
                    MessageCount++;
                    stream = clientSocket.GetStream();
                    bytes  = stream.Read(buffer, 0, buffer.Length);
                    JObject json = JObject.Parse(Encoding.Default.GetString(buffer, 0, bytes));
                    OnReceived?.Invoke(json);
                }
            }
            catch (SocketException se)
            {
                Trace.WriteLine(string.Format("doChat - SocketException : {0}", se.Message));

                if (clientSocket != null)
                {
                    if (OnDisconnected != null)
                    {
                        OnDisconnected(ref clientSocket);
                    }

                    clientSocket.Close();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("doChat - Exception : {0}", ex.Message));

                if (clientSocket != null)
                {
                    if (OnDisconnected != null)
                    {
                        OnDisconnected(ref clientSocket);
                    }

                    clientSocket.Close();
                    stream.Close();
                }
            }
        }
예제 #28
0
        protected void OnNetworkAction(SocketState state)
        {
            if (state.ErrorOccurred)
            {
                OnDisconnected?.Invoke(this);
                return;
            }

            string data = state.GetData();

            OnReceived?.Invoke(this, data);
            state.RemoveData(0, data.Length);
            Networking.GetData(state);
        }
예제 #29
0
 /// <summary>
 /// 接收字节流
 /// </summary>
 /// <param name="param"></param>
 /// <param name="buffer"></param>
 /// <returns></returns>
 public void Receive(string param, byte[] buffer)
 {
     try
     {
         if (OnReceived != null)
         {
             OnReceived.BeginInvoke(param, buffer, null, null);
         }
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("WcfCallback receive error:{0}", ex);
     }
 }
예제 #30
0
        public static void AsyncReceiveFixed(this Socket socket, byte[] buffer, int offset, int len, OnReceived receivedCallback, object state)
        {
            socket.BeginReceive(buffer, offset, len, SocketFlags.None, ar =>
            {
                var received = socket.EndReceive(ar);
                if (received == 0)
                    receivedCallback.Invoke(state, null);

                if (received < len)
                    AsyncReceiveFixed(socket, buffer, offset + received, len - received, receivedCallback, state);
                else
                    receivedCallback.Invoke(state, buffer);

            }, state);
        }
예제 #31
0
        public Task StartAsync(CancellationToken ct = default)
        {
            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);

            _hostTransportTasks = new List <Task>();
            foreach (var hostTransport in _hostTransports)
            {
                hostTransport.OnConnected += (p, e, s) => OnConnected?.Invoke(p, e, s);
                hostTransport.OnReceived  += (p, e, m) => OnReceived?.Invoke(p, e, m);
                hostTransport.OnClosed    += (p, e, s) => OnClosed?.Invoke(p, e, s);
                _hostTransportTasks.Add(hostTransport.StartAsync(ct));
            }

            return(Task.WhenAll(_hostTransportTasks));
        }
예제 #32
0
 public static void AsyncReceiveFixed(this Socket socket, byte[] buffer,
     OnReceived receivedCallback, object state)
 {
     AsyncReceiveFixed(socket, buffer, 0, buffer.Length, receivedCallback, state);
 }