public void ClearTest() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 target.Clear(); Assert.Inconclusive("无法验证不返回值的方法。"); }
private static void ReceivingOperation() { string recStr; try{ while (isConnected) { recStr = streamReader.ReadLine(); if (recStr != null) { Debug.Log("Received: " + recStr); ReceiveQueue.SyncEnqueMsg(recStr); } else { isConnected = false; } } }catch (Exception e) { //ConsoleMsgQueue.EnqueMsg("ReceivingOperation: " + e.Message); } isConnected = false; Debug.Log("Disconnected."); streamReader.Close(); }
private void ReceivingOperation() { string recStr; try{ while (isConnected) { recStr = streamReader.ReadLine(); if (recStr != null) { ConsoleMsgQueue.EnqueMsg("Received: " + recStr, 0); ReceiveQueue.EnqueMsg(new NetworkMessage(recStr)); } else { isConnected = false; } } }catch (Exception e) { ConsoleMsgQueue.EnqueMsg("ReceivingOperation: " + e.Message); } isConnected = false; ConsoleMsgQueue.EnqueMsg("Disconnected."); streamReader.Close(); }
private bool HandleReceiveQueue() { II2NPHeader msg; while (true) { lock ( ReceiveQueue ) { if (ReceiveQueue.Count == 0) { return(true); } msg = ReceiveQueue.Last.Value; ReceiveQueue.RemoveLast(); } switch (msg.MessageType) { case I2NPMessage.MessageTypes.VariableTunnelBuildReply: var vtreply = HandleReceivedTunnelBuild((VariableTunnelBuildReplyMessage)msg.Message); if (!vtreply) { return(false); } break; default: Logging.Log($"OutboundTunnel {TunnelDebugTrace} HandleReceiveQueue: Dropped {msg.MessageType}"); break; } } }
/// <summary> /// Receive consumer using task completion source as notification. /// </summary> /// <param name="ct"></param> /// <returns></returns> public Task ReceiveAsync(CancellationToken ct) { if (_open.IsCancellationRequested || _consumerQueue.IsAddingCompleted) { throw new ProxyException(SocketError.Closed); } Message message; if (ReceiveQueue.TryPeek(out message)) { return(Task.FromResult(true)); } else { // Add cancellable item to signal on completion var tcs = new TaskCompletionSource <bool>(); ct.Register(() => { tcs.TrySetCanceled(); }); try { _consumerQueue.Add(tcs, _open.Token); } catch (OperationCanceledException) { } catch (Exception ex) { // Continue waiting for receives as long as we are not cancelled ProxyEventSource.Log.HandledExceptionAsInformation(this, ex); } ct.ThrowIfCancellationRequested(); return(tcs.Task); } }
async void MessageReceived(byte[] buffer, IPEndPoint endpoint) { await DhtEngine.MainLoop; // Don't handle new messages if we have already stopped the dht engine. if (Listener.Status == ListenerStatus.NotListening) { return; } // I should check the IP address matches as well as the transaction id // FIXME: This should throw an exception if the message doesn't exist, we need to handle this // and return an error message (if that's what the spec allows) try { if (DhtMessageFactory.TryDecodeMessage((BEncodedDictionary)BEncodedValue.Decode(buffer, false), out DhtMessage message)) { Monitor.ReceiveMonitor.AddDelta(buffer.Length); ReceiveQueue.Enqueue(new KeyValuePair <IPEndPoint, DhtMessage> (endpoint, message)); } } catch (MessageException) { // Caused by bad transaction id usually - ignore } catch (Exception) { //throw new Exception("IP:" + endpoint.Address.ToString() + "bad transaction:" + e.Message); } }
/// <summary> /// /// </summary> internal ClientSocketManager( Listener listener, ServiceHandler serviceHandler, ReceiveQueue receiveBuffer ) { if ( listener == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - listener == null error!" ); if ( serviceHandler == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - serviceHandle == null error!" ); if ( receiveBuffer == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - receiveBuffer == null error!" ); m_Listener = listener; m_ServiceHandle = serviceHandler; m_ReceiveBuffer = receiveBuffer; { // 清空数据 m_ReceiveBuffer.Clear(); } m_ServiceHandle.EventProcessData += new EventHandler<ProcessDataAtServerEventArgs>( this.OnListenerProcessMessageBlock ); m_ServiceHandle.EventDisconnect += new EventHandler<DisconnectAtServerEventArgs>( this.OnListenerDisconnect ); // 初始化数据 表示还没调用过Free(...)函数 m_LockFree.SetValid(); }
private IEnumerator DoParse() { int msgCount = 0; int msgCountAcc = 0; float timeAcc = 0; while (true) { msgCount = ReceiveQueue.GetCount(); if (msgCount > 0) { for (int loop = 0; loop < msgCount; loop++) { msgHandler.HandleMsg(ReceiveQueue.SyncDequeMsg()); } } timeAcc += Time.deltaTime; msgCountAcc += msgCount; if (timeAcc > 1) { timeAcc = 0; msgCountAcc = 0; } yield return(null); } }
public string Expect(Regex regex, int timeout = 500) { var cancellationToken = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeout)).Token; while (true) { while (ReceiveQueue.Count == 0 && !cancellationToken.IsCancellationRequested) { Thread.Sleep(10); } if (cancellationToken.IsCancellationRequested) { return(null); } var readline = ReceiveQueue.Dequeue(); if (!readline.Contains("=")) { continue; } if (!regex.IsMatch(readline)) { throw new Exception("Expected string matching " + regex + " but got " + readline + "."); } return(readline); } }
private void PortThread() { while (true) { if (_port.IsOpen) { try { var receive = _port.ReadLine().Replace("\r", "").Replace("\n", ""); if (receive == _heartbeatPhrase) { LastHeartbeatAt = DateTime.Now; } else { ReceiveQueue.Enqueue(receive); } } catch (Exception e) { Debug.WriteLine("PortThread exception: {0}", e); Thread.Sleep(1); } } else { Thread.Sleep(1); } } }
public void OutProcessReceiveTest() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 target.OutProcessReceive(); Assert.Inconclusive("无法验证不返回值的方法。"); }
/// <summary> /// Read responses from socket /// </summary> /// <param name="ct"></param> /// <returns></returns> public async Task <BrowseResponse> BrowseNextAsync(CancellationToken ct) { if (!_connected) { throw new SocketException(SocketError.Closed); } Message message; while (!ReceiveQueue.TryDequeue(out message)) { await ReceiveAsync(ct).ConfigureAwait(false); } ProxySocket.ThrowIfFailed(message); if (message.Error != (int)SocketError.Success) { throw new SocketException((SocketError)message.Error); } if (message.TypeId != MessageContent.Data) { throw new SocketException("No data message"); } var data = message.Content as DataMessage; if (data == null) { throw new SocketException("Bad data"); } var stream = new MemoryStream(data.Payload); var response = await BrowseResponse.DecodeAsync(stream, _codec, ct); response.Interface = message.Proxy.ToSocketAddress(); return(response); }
protected virtual void OnReceive(TCPClient client, int numberOfBytesReceived) { if (numberOfBytesReceived <= 0) { this.Status = SocketStatus.SOCKET_STATUS_NO_CONNECT; this.OnDisconnect(client); } else { #if DEBUG //CrestronConsole.PrintLine("{0}.OnReceive() numberOfBytesReceived = {1}, Enqueuing...", this.GetType().Name, numberOfBytesReceived); #endif for (int b = 0; b < numberOfBytesReceived; b++) { ReceiveQueue.Enqueue(client.IncomingDataBuffer[b]); if (_receiveThread == null || _receiveThread.ThreadState == Thread.eThreadStates.ThreadFinished) { _receiveThread = new Thread(ReceiveThreadProcess, null, Thread.eThreadStartOptions.CreateSuspended); _receiveThread.Priority = Thread.eThreadPriority.UberPriority; _receiveThread.Name = string.Format("{0} Rx Handler", this.GetType().Name); _receiveThread.Start(); } } if (client.ClientStatus == SocketStatus.SOCKET_STATUS_CONNECTED) { client.ReceiveDataAsync(OnReceive); } } }
public static void Main(string[] args) { ReceiveQueue.Start(PacketHandler.Handle); ServerSocket.Start(13338); Console.WriteLine($"Server running!"); var t = new Thread(() => { Console.WriteLine($"Heartbeat Thread started."); while (true) { foreach (var kvp in Collections.Players) { var player = kvp.Value; if (DateTime.Now >= player.LastPing.AddSeconds(1)) { Console.WriteLine($"Sending Ping to {player.Name}/{player.Username}."); player.Socket.Send(MsgPing.Create(player.UniqueId)); player.LastPing = DateTime.Now; } } Thread.Sleep(1); } }); t.Start(); while (true) { Console.ReadLine(); } }
internal bool Close() { // ?! //SpinLock.Enter(); bool result = Interlocked.Increment(ref closeCount) == 1; //SpinLock.Exit(); if (result) { ReceiveQueue.Dispose(); if (sspiContext != null) { sspiContext.Dispose(); } if (UserConnection != null) { UserConnection.Dispose(); } } return(result); }
private bool HandleReceiveQueue() { TunnelDataMessage[] tdmsgs = null; lock ( ReceiveQueue ) { if (ReceiveQueue.Count == 0) { return(true); } if (ReceiveQueue.Any(mq => mq.MessageType == I2NPMessage.MessageTypes.TunnelData)) { var removelist = ReceiveQueue.Where(mq => mq.MessageType == I2NPMessage.MessageTypes.TunnelData); tdmsgs = removelist.Select(mq => (TunnelDataMessage)mq.Message).ToArray(); } ReceiveQueue.Clear(); // Just drop the non-TunnelData } if (tdmsgs != null) { return(HandleTunnelData(tdmsgs)); } return(true); }
internal static void Received(object sender, SocketAsyncEventArgs e) { Start: var token = (ClientSocket)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { try { ReceiveQueue.Add(e); token.ReceiveSync.WaitOne(); if (!token.Socket.ReceiveAsync(e)) { goto Start; } } catch (Exception exception) { Console.WriteLine(exception); CloseClientSocket(e); } } else { CloseClientSocket(e); } }
/// <summary> /// /// </summary> internal ClientSocketManager( Listener listener, ServiceHandler serviceHandler, ReceiveQueue receiveBuffer ) { if ( listener == null ) throw new ArgumentNullException( "listener", "ClientSocketHandler.ClientSocketManager(...) - listener == null error!" ); if ( serviceHandler == null ) throw new ArgumentNullException( "serviceHandler", "ClientSocketHandler.ClientSocketManager(...) - serviceHandle == null error!" ); if ( receiveBuffer == null ) throw new ArgumentNullException( "receiveBuffer", "ClientSocketHandler.ClientSocketManager(...) - receiveBuffer == null error!" ); m_Listener = listener; m_ServiceHandle = serviceHandler; m_ReceiveBuffer = receiveBuffer; { // ������� m_ReceiveBuffer.Clear(); } m_ServiceHandle.EventProcessData += OnListenerProcessMessageBlock; m_ServiceHandle.EventDisconnect += OnListenerDisconnect; // ��ʼ������ ��ʾ��û���ù�Free(...)���� m_LockFree.SetValid(); }
internal void Completed(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { Disconnect("ClientSocket.Completed() e.SocketError != SocketError.Success"); return; } switch (e.LastOperation) { case SocketAsyncOperation.Receive: ReceiveQueue.Add(this); break; case SocketAsyncOperation.Send: SendSync.Set(); break; case SocketAsyncOperation.Connect: IsConnected = true; OnConnected?.Invoke(); Receive(); break; } }
public void FreeTest() { Listener target = new Listener(); // TODO: 初始化为适当的值 ReceiveQueue receiveQueue = null; // TODO: 初始化为适当的值 target.Free(receiveQueue); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void LengthTest() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 long actual; actual = target.Length; Assert.Inconclusive("验证此测试方法的正确性。"); }
public void ConnectAsync(string ip, ushort port) { ThreadedConsole.WriteLine("Connecting to Server..."); ReceiveQueue.Start(OnPacket); Socket = new ClientSocket(this); Socket.OnDisconnect += Disconnected; Socket.OnConnected += Connected; Socket.ConnectAsync(ip, port); }
public void Disconnect() { if (_port.IsOpen) { _port.Close(); } IsConnected = false; ReceiveQueue.Clear(); }
public void Close() { _cts.Cancel(); CloseLock.EnterWriteLock(); IsClosed = true; CloseLock.ExitWriteLock(); ReceiveQueue.Dispose(); }
public void InitClientHandlerTest1() { ClientSocketManager target = new ClientSocketManager(); // TODO: 初始化为适当的值 Listener listener = null; // TODO: 初始化为适当的值 ServiceHandle serviceHandle = null; // TODO: 初始化为适当的值 ReceiveQueue receiveBuffer = null; // TODO: 初始化为适当的值 target.InitClientHandler(listener, serviceHandle, receiveBuffer); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void InitClientHandlerTest() { ClientSocketManager target = new ClientSocketManager(); // TODO: 初始化为适当的值 Connecter connecter = null; // TODO: 初始化为适当的值 ConnectHandle connectHandle = ConnectHandle.Zero; // TODO: 初始化为适当的值 ReceiveQueue receiveBuffer = null; // TODO: 初始化为适当的值 target.InitClientHandler(connecter, connectHandle, receiveBuffer); Assert.Inconclusive("无法验证不返回值的方法。"); }
public void GetPacketIDTest() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 long expected = 0; // TODO: 初始化为适当的值 long actual; actual = target.GetPacketID(); Assert.AreEqual(expected, actual); Assert.Inconclusive("验证此测试方法的正确性。"); }
public void EnqueueTest1() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 IntPtr byteBuffer = new IntPtr(); // TODO: 初始化为适当的值 long iOffset = 0; // TODO: 初始化为适当的值 long iSize = 0; // TODO: 初始化为适当的值 target.Enqueue(byteBuffer, iOffset, iSize); Assert.Inconclusive("无法验证不返回值的方法。"); }
public virtual void MessageReceived(I2NPMessage msg, int recvdatasize) { #if LOG_ALL_TUNNEL_TRANSFER Logging.LogDebug($"{this}: MessageReceived {msg.Message}"); #endif Bandwidth.DataReceived(recvdatasize); //Logging.LogDebug( $"{this}: MessageReceived {msg.MessageType} TDM len {recvsize}" ); ReceiveQueue.Enqueue(msg); }
public void InProcessReceiveTest() { ReceiveQueue target = new ReceiveQueue(); // TODO: 初始化为适当的值 bool expected = false; // TODO: 初始化为适当的值 bool actual; actual = target.InProcessReceive(); Assert.AreEqual(expected, actual); Assert.Inconclusive("验证此测试方法的正确性。"); }
private void M_SocketManager_ReceiveClientData(Net.AsyncUserToken token, byte[] buff) { if (buff.Length > 0 && buff[0] == 0x5a) { ReceiveQueue.Enqueue(new WHQueueModel(buff, token.IPAddress.ToString())); string vOutInfo = string.Format("电源收到一组数据,IP地址({0}):{1}", token.IPAddress.ToString(), BitConverter.ToString(buff)); Console.WriteLine(vOutInfo); LogHelper.WriteLog_Debug(typeof(PowerControl), vOutInfo); } }
public CommMessage GetMessage() { CommMessage msg = ReceiveQueue.DeQ(); if (msg.Type == CommMessage.MessageType.CloseReceiver) { Close(); } return(msg); }
/// <summary> /// /// </summary> internal ClientSocketManager( Connecter connecter, ConnectHandler connectHandler, ReceiveQueue receiveBuffer ) { if ( connecter == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - listener == null error!" ); if ( connectHandler == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - serviceHandle == null error!" ); if ( receiveBuffer == null ) throw new Exception( "ClientSocketHandler.ClientSocketManager(...) - receiveBuffer == null error!" ); m_Connecter = connecter; m_ConnectHandle = connectHandler; m_ReceiveBuffer = receiveBuffer; { // 清空数据 m_ReceiveBuffer.Clear(); } // 初始化数据 表示还没调用过Free(...)函数 m_LockFree.SetValid(); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="useQueue"> Property to optionally bypass the queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState, UseQueue useQueue) { //_sendCommandLogger.LogLine(sendCommand.CommandString()); var synchronizedSend = (sendCommand.ReqAc || useQueue == UseQueue.BypassQueue); if (sendQueueState == SendQueue.ClearQueue ) { // Clear receive queue _receiveCommandQueue.Clear(); } if (receiveQueueState == ReceiveQueue.ClearQueue ) { // Clear send queue _sendCommandQueue.Clear(); } // If synchronized sending, the only way to get command at end of queue is by waiting if (sendQueueState == SendQueue.WaitForEmptyQueue || (synchronizedSend && sendQueueState == SendQueue.AtEndQueue) ) { while (_sendCommandQueue.Count > 0) Thread.Sleep(1); } if (receiveQueueState == ReceiveQueue.WaitForEmptyQueue) { while (_receiveCommandQueue.Count>0) Thread.Sleep(1); } if (synchronizedSend) { return SendCommandSync(sendCommand, sendQueueState); } if (sendQueueState != SendQueue.AtEndQueue) { // Put command at top of command queue _sendCommandQueue.SendCommand(sendCommand); } else { // Put command at bottom of command queue _sendCommandQueue.QueueCommand(sendCommand); } return new ReceivedCommand(); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="useQueue"> Property to optionally bypass the queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState, UseQueue useQueue) { var synchronizedSend = (sendCommand.ReqAc || useQueue == UseQueue.BypassQueue); // When waiting for an acknowledge, it is typically best to wait for the ReceiveQueue to be empty // This is thus the default state if (sendCommand.ReqAc && receiveQueueState == ReceiveQueue.Default) { receiveQueueState = ReceiveQueue.WaitForEmptyQueue; } if (sendQueueState == SendQueue.ClearQueue ) { // Clear receive queue _receiveCommandQueue.Clear(); } if (receiveQueueState == ReceiveQueue.ClearQueue ) { // Clear send queue _sendCommandQueue.Clear(); } // If synchronized sending, the only way to get command at end of queue is by waiting if (sendQueueState == SendQueue.WaitForEmptyQueue || (synchronizedSend && sendQueueState == SendQueue.AtEndQueue) ) { SpinWait.SpinUntil(() => _sendCommandQueue.IsEmpty); } if (receiveQueueState == ReceiveQueue.WaitForEmptyQueue) { SpinWait.SpinUntil(() => _receiveCommandQueue.IsEmpty); } if (synchronizedSend) { return SendCommandSync(sendCommand, sendQueueState); } if (sendQueueState != SendQueue.AtEndQueue) { // Put command at top of command queue _sendCommandQueue.SendCommand(sendCommand); } else { // Put command at bottom of command queue _sendCommandQueue.QueueCommand(sendCommand); } return new ReceivedCommand { CommunicationManager = _communicationManager }; }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState = SendQueue.InFrontQueue, ReceiveQueue receiveQueueState = ReceiveQueue.Default) { return SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue); }
/// <summary> /// 释放指定的客户端到内存池里面 /// </summary> /// <param name="clientSocketHandler"></param> internal void Free( ReceiveQueue receiveQueue ) { // 返回至内存池(ClientSocketHandler) m_ReceiveQueuePool.ReleasePoolContent( receiveQueue ); }
/// <summary> Sends a command. /// If no command acknowledge is requested, the command will be send asynchronously: it will be put on the top of the send queue /// If a command acknowledge is requested, the command will be send synchronously: the program will block until the acknowledge command /// has been received or the timeout has expired. /// Based on ClearQueueState, the send- and receive-queues are left intact or are cleared</summary> /// <param name="sendCommand"> The command to sent. </param> /// <param name="sendQueueState"> Property to optionally clear/wait the send queue</param> /// <param name="receiveQueueState"> Property to optionally clear/wait the send queue</param> /// <returns> A received command. The received command will only be valid if the ReqAc of the command is true. </returns> public ReceivedCommand SendCommand(SendCommand sendCommand, SendQueue sendQueueState, ReceiveQueue receiveQueueState) { return SendCommand(sendCommand, sendQueueState, receiveQueueState, UseQueue.UseQueue); }
/// <summary> /// /// </summary> internal ClientSocketManager( Connecter connecter, ConnectHandler connectHandler, ReceiveQueue receiveBuffer ) { if ( connecter == null ) throw new ArgumentNullException( "ClientSocketHandler.ClientSocketManager(...) - listener == null error!" ); if ( connectHandler == null ) throw new ArgumentNullException( "ClientSocketHandler.ClientSocketManager(...) - serviceHandle == null error!" ); if ( receiveBuffer == null ) throw new ArgumentNullException( "receiveBuffer", "ClientSocketHandler.ClientSocketManager(...) - receiveBuffer == null error!" ); m_Connecter = connecter; m_ConnectHandle = connectHandler; m_ReceiveBuffer = receiveBuffer; { // ������� m_ReceiveBuffer.Clear(); } // ��ʼ������ ��ʾ��û���ù�Free(...)���� m_LockFree.SetValid(); }