private async void WaitForIncommingData() { var buffer = new byte[100000]; try { while (Client.Connected) { var readLength = await stream.ReadAsync(buffer, 0, buffer.Length); if (readLength > 0) { var actualBytes = new byte[readLength]; Array.Copy(buffer, 0, actualBytes, 0, actualBytes.Length); ReceivedData?.Invoke(this, new ReceivedDataEventArgs { Data = actualBytes }); } else { break; } } } catch { } finally { TriggerClosedEvent(); } }
private async Task ReceiveLoop(TcpClient client) { using (Stream networkStream = client.GetStream()) { while (true) { byte[] data = await ReadMessageAsync(networkStream); if (data == null) { break; } try { // we received some data, raise event ReceivedData?.Invoke(data); } catch (Exception exception) { ReceivedError?.Invoke(exception); } } } }
/// <summary> /// Listens for and handles all incoming transmissions. /// </summary> private void Listener() { while (true) { Console.WriteLine("Waiting for connection"); TcpClient lClient = _internalServer.AcceptTcpClient(); Console.WriteLine("Incoming connection from {0}", ((IPEndPoint)lClient.Client.RemoteEndPoint).Address.ToString()); //connectedClients.Add(((IPEndPoint)lClient.Client.RemoteEndPoint).Address.ToString()); NetworkStream stream = lClient.GetStream(); byte[] bytes = new byte[256]; string data = null; int i; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { data = Encoding.ASCII.GetString(bytes, 0, i); ReceivedDataEventArgs e = new ReceivedDataEventArgs(); e.Data = data; ReceivedData?.Invoke(this, e); // that's a neat shortcut tbh } stream.Close(); lClient.Close(); Console.WriteLine("Connection closed"); } }
/// <summary> /// Sends data to the currently connected device /// </summary> /// <param name="data">Data to send</param> public void SendData(string data) { if (btDevice == null) { return; } try { // Create a RFCOMM socket and connect var socket = btDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString(BtDeviceInfo.RequiredServiceID)); socket.Connect(); // Setup receiving data before sending any data to the server var streamAndData = new StreamAndData(socket.InputStream); streamAndData.stream.BeginRead(streamAndData.data, 0, streamAndData.data.Length, new AsyncCallback((ar) => { var asyncState = (StreamAndData)ar.AsyncState; var bytesRead = streamAndData.stream.EndRead(ar); var incomingData = Encoding.ASCII.GetString(streamAndData.data, 0, bytesRead); ReceivedData?.Invoke(this, incomingData); }), streamAndData); // Send the data using (var sw = new StreamWriter(socket.OutputStream)) { sw.Write(data); } } catch (Exception ex) { ReceivedData?.Invoke(this, $"msg:{ex.ToString()}"); } }
public void OnReceivedData(byte[] data) { ReceivedDataEventArgs receivedArgs = new ReceivedDataEventArgs(); receivedArgs.ReceivedData = data; ReceivedData?.Invoke(this, receivedArgs); }
async Task ReceiveLoop(WebSocket webSocket, CancellationToken token) { byte[] buffer = new byte[MaxMessageSize]; while (true) { WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), token); if (result == null) { break; } if (result.MessageType == WebSocketMessageType.Close) { break; } // we got a text or binary message, need the full message ArraySegment <byte> data = await ReadFrames(result, webSocket, buffer); if (data.Count == 0) { break; } try { ReceivedData?.Invoke(data); } catch (Exception exception) { ReceivedError?.Invoke(exception); } } }
/// <summary> /// Multiple Voltron packets were sent in a Aries frame. /// </summary> /// <param name="PacketBuf">The packet buffer containing the packets to process.</param> private void ProcessVoltronPackets(Client Client, byte[] PacketBuf) { VoltronHeader Header = ReadVoltronHeader(PacketBuf, 12); MemoryStream AriesStream = new MemoryStream(PacketBuf); EndianBinaryReader Reader = new EndianBinaryReader(new BigEndianBitConverter(), AriesStream); int Remaining = (int)AriesStream.Length - 12; byte[] AriesHeader = Reader.ReadBytes(12); //Aries header. while (Header.PacketSize < Remaining) { byte[] VoltronBody = Reader.ReadBytes((int)Header.PacketSize); VoltronPacket Packet = new VoltronPacket(ReconstructVoltronPacket(AriesHeader, VoltronBody), true); lock (Client.ReceivedPackets) Client.ReceivedPackets.Enqueue(Packet); Remaining -= (int)Header.PacketSize; if (Header.PacketSize < Remaining) { Header = ReadVoltronHeader(AriesStream.ToArray(), (int)(AriesStream.Position)); } } Reader.Close(); ReceivedData?.Invoke(this, Client); }
private void consumer_Listener(IMessage message) { ITextMessage msg = (ITextMessage)message; if (ReceivedData != null) { ReceivedData.Invoke(msg); } }
private void RaiseReceivedData(ReceivedData data) { if (!Validator.TryValidateObject(data, new ValidationContext(data), null, true)) { return; } ReceivedData?.Invoke(this, new ChannelDataReceivedEventArgs(data)); }
async Task ReceiveLoopAsync(WebSocket webSocket, CancellationToken token) { int connectionId = NextConnectionId(); clients.Add(connectionId, webSocket); byte[] buffer = new byte[MaxMessageSize]; try { // someone connected, raise event Connected?.Invoke(connectionId); while (true) { WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), token); if (!enabled) { await WaitForEnabledAsync(); } if (result.MessageType == WebSocketMessageType.Close) { Debug.Log($"Client initiated close. Status: {result.CloseStatus} Description: {result.CloseStatusDescription}"); break; } ArraySegment <byte> data = await ReadFrames(connectionId, result, webSocket, buffer, token); if (data.Count == 0) { break; } try { // we received some data, raise event ReceivedData?.Invoke(connectionId, data); } catch (Exception exception) { ReceivedError?.Invoke(connectionId, exception); } } } catch (Exception exception) { ReceivedError?.Invoke(connectionId, exception); } finally { clients.Remove(connectionId); Disconnected?.Invoke(connectionId); } }
public void BeginReceive() { Task.Factory.StartNew(() => { while (true) { Task <byte[]> task = Receive(); task.Wait(); ReceivedData?.Invoke(task.Result); } }, cancellationTokenSource.Token); }
public void ReceiveDataFromSource(RoutingEventArgs e) { if (ReceivedData != null) { ReceivedData.Invoke(this, new RoutingEventArgs { Buffer = e.Buffer, Count = e.Count, Format = e.Format, Index = index }); } }
public void Start() { listener.Start(); Task.Factory.StartNew(() => { while (true) { var task = Receive(); task.Wait(); var context = task.Result; ReceivedData?.Invoke(context); } }, cancellationTokenSource.Token); }
private void StartListening() { NetworkStream stream = client.GetStream(); while (client.Connected) { byte[] buffer = new byte[1024]; int length = stream.Read(buffer, 0, buffer.Length); ReceivedDataEventArgs args = new ReceivedDataEventArgs(buffer.SubArray(0, length)); ReceivedData?.Invoke(this, args); } }
/// <summary> /// Multiple Voltron packets were sent in a Aries frame. /// </summary> /// <param name="PacketBuf">The packet buffer containing the packets to process.</param> private void ProcessVoltronPackets(Client C, byte[] PacketBuf) { VoltronHeader Header = ReadVoltronHeader(PacketBuf, 12); MemoryStream AriesStream = new MemoryStream(PacketBuf); EndianBinaryReader Reader = new EndianBinaryReader(new LittleEndianBitConverter(), AriesStream); int Remaining = (int)(AriesStream.Length - 1) - 12; byte[] AriesHeader = Reader.ReadBytes(12); //Aries header. Reader = new EndianBinaryReader(new BigEndianBitConverter(), AriesStream); Reader.BaseStream.Position = 12; //We've already read the header. while (Header.PacketSize < Remaining) { byte[] VoltronData = Reader.ReadBytes((int)Header.PacketSize); if (Header.PacketType == 0x0044) { SplitBufferPDU SplitBufferPacket; SplitBufferPacket = new SplitBufferPDU(VoltronData, false); lock (C.ReceivedSplitBuffers) C.ReceivedSplitBuffers.Enqueue(SplitBufferPacket); if (SplitBufferPacket.EOF == 1) { CompileVoltronPackets(C); } } else { VoltronPacket Packet = new VoltronPacket(ReconstructVoltronPacket(AriesHeader, VoltronData), true); lock (C.ReceivedPackets) C.ReceivedPackets.Enqueue(Packet); } Remaining -= (int)Header.PacketSize; if (Header.PacketSize < Remaining) { Header = ReadVoltronHeader(AriesStream.ToArray(), (int)(AriesStream.Position)); } } Reader.Close(); ReceivedData?.Invoke(this, C); }
private void PacketParser_PacketComplete(object sender, PrinterPacketParserPacketCompleteEventArgs e) { if (_commandStack.Count > 0 && !_commandStack.Peek().Acknowledged) { _commandStack.Peek().ResponsePacketQueue.Enqueue(e.Packet); if (e.Packet.IsAck) { _commandStack.Peek().Acknowledged = true; _commandStack.Peek().AcknowledgedAt = DateTime.UtcNow; } } ReceivedData?.Invoke(this, new PrinterControllerReceivedDataEventArgs() { Packet = e.Packet }); }
private async Task ReceiveLoop(TcpClient tcpClient) { int connectionId = NextConnectionId(); clients.Add(connectionId, tcpClient); try { // someone connected, raise event Connected?.Invoke(connectionId); using (Stream networkStream = tcpClient.GetStream()) { while (true) { byte[] data = await ReadMessageAsync(networkStream); if (data == null) { break; } try { // we received some data, raise event ReceivedData?.Invoke(connectionId, data); } catch (Exception exception) { ReceivedError?.Invoke(connectionId, exception); } } } } catch (Exception exception) { ReceivedError?.Invoke(connectionId, exception); } finally { clients.Remove(connectionId); Disconnected?.Invoke(connectionId); } }
private async Task Receive(WebSocket webSocket, CancellationToken token) { var buffer = new byte[int.MaxValue]; while (true) { WebSocketReceiveResult result = await webSocket.ReceiveAsync(new System.ArraySegment <byte>(buffer), token); if (result == null) { break; } if (result.MessageType == WebSocketMessageType.Close) { break; } byte[] data = await ReadFrames(result, webSocket, buffer); if (data == null) { break; } try { ReceivedData.Invoke(data); //var msg = ProcessJsonToDetourMessage(data, data.Length); //if (msg != null) //{ // ReceivedMessage(msg); //} } catch (Newtonsoft.Json.JsonReaderException ex) { Debug.LogError(ex); } catch (System.Exception ex) { Debug.LogError(ex); } } }
private void CompileVoltronPackets(Client C) { MemoryStream OutputStream = new MemoryStream(); EndianBinaryReader Reader; EndianBinaryWriter Writer; AriesHeader AHeader = new AriesHeader(); AHeader.PacketSize = m_PacketSize; AHeader.PacketType = m_PacketType; //Reassemble all the Voltron packets. for (int i = 0; i < C.ReceivedSplitBuffers.Count; i++) { SplitBufferPDU SplitBuffer; C.ReceivedSplitBuffers.TryDequeue(out SplitBuffer); Reader = new EndianBinaryReader(new BigEndianBitConverter(), OutputStream); Writer = new EndianBinaryWriter(new BigEndianBitConverter(), OutputStream); Writer.Write(Reader.ReadBytes((int)SplitBuffer.FragmentSize)); Writer.Flush(); } MemoryStream VoltronPackets = new MemoryStream(OutputStream.ToArray()); uint BufSize = (uint)VoltronPackets.Length; for (int i = 0; i < BufSize; i++) { Reader = new EndianBinaryReader(new BigEndianBitConverter(), VoltronPackets); VoltronHeader Header = ReadVoltronHeader(Reader.ReadBytes(12)); Reader.BaseStream.Position = 0; //Backtrack to beginning of stream. VoltronPacket VPacket = new VoltronPacket( ReconstructVoltronPacket(AHeader, Reader.ReadBytes((int)Header.PacketSize)), true); C.ReceivedPackets.Enqueue(VPacket); BufSize -= Header.PacketSize; ReceivedData?.Invoke(this, C); } }
public void StartListening() { using var server = new NamedPipeServerStream(applicationId); server.WaitForConnection(); using var reader = new BinaryReader(server, Encoding.UTF8); var argsCount = reader.ReadInt32(); var args = new string[argsCount]; for (int i = 0; i < argsCount; i++) { args[i] = reader.ReadString(); } ReceivedData?.Invoke(this, new Data { Arguments = args }); server.Close(); StartListening(); // listen to another publisher }
/// <summary> /// 收到数据时调用 /// </summary> protected virtual void OnReceived() { ReceivedData?.Invoke(this); }
private void OnDataReceived(object sender, System.EventArgs e) { ReceivedData?.Invoke(DataBaseWorker.GetDataByNumber(ObjectId, Count)); Count++; }
/** * @brief ProcessData Функция обработки набора данных * @param buf Указатель на массив данных * @param size Размер данных */ protected void ProcessData(ref List <byte> buf, int size) { //Debug.WriteLine("ProcessData: {0}", buf.Count); GARANT_EEG_DATA frameData = new GARANT_EEG_DATA(); if (m_Rate == 250) { frameData.DataRecordsCount = 25; } else if (m_Rate == 500) { frameData.DataRecordsCount = 50; } else if (m_Rate == 1000) { frameData.DataRecordsCount = 100; } if (m_Recording && !m_RecordPaused && m_File != null) { if (m_FileWriteBuffer.Count > WRITE_FILE_BUFFER_SIZE) { m_File.Write(m_FileWriteBuffer.ToArray(), 0, m_FileWriteBuffer.Count); } m_FileWriteBuffer.AddRange(buf.Take(size)); m_WrittenDataCount++; } for (int i = 0; i < 22; i++) { if (i < 8) //main channels { int ptr = (i * frameData.DataRecordsCount * 3); for (int j = 0; j < frameData.DataRecordsCount; j++, ptr += 3) { //frameData.ChannelsData[j].Value[i] = (int)(unpack24BitValue(ptr) * 0.000447) / 10.0; // из кода matlab double v = (Unpack24BitValue(ref buf, ptr) * 0.000447) / 10.0 / 1000.0; frameData.RawChannelsData[j].Value[i] = v; frameData.FilteredChannelsData[j].Value[i] = v; // /1000.0 для перевода в микровольты (из милливольт) } } else if (i < 11) //accelerometr { //uchar *ptr = buf + ((8 * frameData.Channels.size() * 3) + (i - 8) * frameData.Accelerometr.size() * 3); } else if (i < 21) //rx { int ptr = ((8 * frameData.DataRecordsCount * 3 + 3 * 5 * 3) + (i - 11) * 1 * 3); for (int j = 0; j < 1; j++, ptr += 3) { double val = (Unpack24BitValue(ref buf, ptr) * 0.0677) / 10.0; int pos = i - 11; if (pos < 8) { frameData.ResistanceData.Value[pos] = val; } else if (pos == 8) { frameData.ResistanceData.Ref = val; } else { frameData.ResistanceData.Ground = val; } } } else { //annotations //uchar *ptr = buf + ((8 * frameData.Channels.size() * 3 + 3 * frameData.Accelerometr.size() * 3) + 10 * frameData.RX.size() * 3); } } buf.RemoveRange(0, size - 90); string jsonData = System.Text.Encoding.ASCII.GetString(buf.ToArray()); //Debug.WriteLine("data.ToString() => {0} {1}", buf.Count, jsonData); Dictionary <string, object> data = jsonData.Decode <Dictionary <string, object> >(); if (data != null) { if (data.ContainsKey("FW Version")) { m_FirmwareVersion = data["FW Version"].ToString(); //Debug.WriteLine("FW Version: {0}", m_FirmwareVersion); } if (data.ContainsKey("Battery %")) { m_BatteryStatus = int.Parse(data["Battery %"].ToString()); //Debug.WriteLine("Battery %: {0}", m_BatteryStatus); } if (data.ContainsKey("Block's Time")) { frameData.Time = double.Parse(data["Block's Time"].ToString()); //Debug.WriteLine("Block's Time: {0}", frameData.Time); } } if (m_Filters.Count > 0) { foreach (var filter in m_Filters) { if (filter == null) { continue; } float[][] channels = new float[8][]; for (int i = 0; i < 8; i++) { channels[i] = new float[frameData.DataRecordsCount]; } float multiply = 1.0f; /*int index = ui->comboBoxVoltage->currentIndex(); * if(0 == index) * { * multiply = 1000000.0; * } * else if(1 == index) * { * multiply = 1000.0; * }*/ for (int i = 0; i < 8; i++) { for (int j = 0; j < frameData.DataRecordsCount; j++) { float value = (float)frameData.RawChannelsData[j].Value[i]; if (Math.Abs(value * 1000000) >= 374000) { value = 0.0f; } else { value *= multiply; } channels[i][j] = value; } filter.Process(channels[i]); } for (int i = 0; i < 8; i++) { for (int j = 0; j < frameData.DataRecordsCount; j++) { frameData.FilteredChannelsData[j].Value[i] = (double)channels[i][j]; } } } } ReceivedData.Invoke(this, frameData); }
private void DoReceivedData(byte[] data) { ReceivedData?.Invoke(this, new BluetoothDataReceivedEventArgs(data)); }
private async void RunAsync() { if (_Udp == null) { int tryTimes = 0; while (tryTimes < 100) { try { _Udp = new UdpClient(NetworkPortManager.Port); break; } catch (Exception) { tryTimes++; } } } _Udp.Client.ReceiveBufferSize = 1024 * 1024; _Udp.Client.SendBufferSize = 1024 * 1024; // 处理异常 // System.Net.Sockets.SocketException:远程主机强迫关闭了一个现有的连接。 uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; _Udp.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); while (IsAlive) { try { var udpReceiveResult = await _Udp.ReceiveAsync(); if (udpReceiveResult != null && udpReceiveResult.Buffer != null) { if (_StreamBuffer.Length == _StreamBuffer.Capacity) { _StreamBuffer.Reset(); } _StreamBuffer.Write(udpReceiveResult.Buffer, 0, udpReceiveResult.Buffer.Length); } if (ReceivedData != null) { ReceivedData.Invoke(udpReceiveResult.Buffer, udpReceiveResult.RemoteEndPoint); } await Task.Delay(100); } catch (Exception) { if (!IsAlive || _Udp == null) { break; } } } }
private void ProcessBuffer(Client C) { lock (m_LockingObj) //The following code won't execute unless it's able to acquire a lock. { while (m_CurrentlyReceived >= m_PacketSize) { byte[] PacketBuf = new byte[m_PacketSize]; if (!m_PartialPacketReceived) { Array.Copy(C.Buffer, PacketBuf, m_PacketSize); } else //The slushbuffer wasn't empty, so combine the two buffers into a packet buffer. { Array.ConstrainedCopy(C.SlushBuffer, 0, PacketBuf, 0, m_SizeOfSlush); Array.ConstrainedCopy(C.Buffer, 0, PacketBuf, m_SizeOfSlush, m_CurrentlyReceived); C.CreateSlushBuffer(0); m_SizeOfSlush = 0; m_PartialPacketReceived = false; } if (m_PacketType != 0) { lock (C.ReceivedPackets) C.ReceivedPackets.Enqueue(new AriesPacket(PacketBuf, true)); m_CurrentlyReceived -= (int)m_PacketSize; ReceivedData?.Invoke(this, C); } else { VoltronHeader Header = ReadVoltronHeader(PacketBuf, 12); if (Header.PacketSize < ((PacketBuf.Length - 1) - 12)) { ProcessVoltronPackets(C, PacketBuf); } else { lock (C.ReceivedPackets) C.ReceivedPackets.Enqueue(new VoltronPacket(PacketBuf, true)); ReceivedData?.Invoke(this, C); } m_CurrentlyReceived -= (int)m_PacketSize; } if (m_CurrentlyReceived > 0) { byte[] Remainder = new byte[m_CurrentlyReceived]; Array.ConstrainedCopy(C.Buffer, (C.Buffer.Length - m_CurrentlyReceived) + 1, Remainder, 0, m_CurrentlyReceived); m_SizeOfSlush = m_CurrentlyReceived; C.CreateBuffer(BUFFER_SIZE); C.CreateSlushBuffer(m_SizeOfSlush); Array.Copy(Remainder, C.SlushBuffer, m_CurrentlyReceived); Remainder = null; m_PartialPacketReceived = true; } else { C.CreateBuffer(BUFFER_SIZE); } } } }
private void ReaderRun(TcpClient client) { NetworkStream stream = null; EndPoint endPoint = client.Client.RemoteEndPoint; LogInfo($"Client {endPoint} connected"); byte[] data = new byte[MaxLength]; stream = client.GetStream(); IFormatter formatter = new BinaryFormatter(); while (true) { LogInfo($"Reading input from {endPoint}..."); int len = 0; try { len = stream.Read(data, 0, sizeof(int)); } catch { } if (len == 0) { break; } int dataSize = BitConverter.ToInt32(data, 0); len = 0; int curLen = 0; while (len < dataSize) { try { curLen = stream.Read(data, len, dataSize - len); len += curLen; } catch { } if (curLen == 0) { break; } } if (curLen == 0) { break; } System.Diagnostics.Debug.Assert(len == dataSize && dataSize < MaxLength); string func; object[] ps; using (var serStream = new MemoryStream(data)) { func = (string)formatter.Deserialize(serStream); ps = (object[])formatter.Deserialize(serStream); } LogInfo($"Reading input from {endPoint} finished. Firing event..."); OnReceivedData(endPoint, func, ps); ReceivedData?.Invoke( this, new EventArgs <EndPoint, Invocation>( endPoint, new Invocation { FuncName = func, Parameters = ps } ) ); //LogInfo($"Reading input from {endPoint} finished. Firing event finished."); } LogInfo($"Client {endPoint} disconnected"); remoteClients.TryRemove(endPoint, out var _); ClientDisconnected?.Invoke(this, new EventArg <EndPoint>(endPoint)); }
protected virtual void OnReceivedData(byte[] data) { ReceivedData?.Invoke(this, data); }
protected void OnBytesReceived(IAsyncResult result) { int nBytesRec; try { nBytesRec = this.sock.EndReceive(result); } catch { try { this.sock.Close(); } catch { } if (Disconnected != null) { Disconnected(null, new ConnectionEventArgs() { }); } return; } if (nBytesRec <= 0) { try { this.sock.Close(); } catch { } if (Disconnected != null) { Disconnected(null, new ConnectionEventArgs() { }); } return; } byte[] receivedBytes = new byte[nBytesRec]; for (int i = 0; i < nBytesRec; i++) { receivedBytes[i] = dataRcvBuf[i]; } if (nBytesRec > 0) { ReceivedData.Invoke(this, new MessageEventArgs() { data = receivedBytes }); } st.Reset(); st.Start(); this.sock.BeginReceive( this.dataRcvBuf, 0, this.dataRcvBuf.Length, SocketFlags.None, new AsyncCallback(this.OnBytesReceived), this); }