/// <summary> /// Reads socket and processes packet /// </summary> /// <param name="socket">The active socket.</param> protected virtual void OnSocket(Socket socket) { try { if (socket.Poll(-1, SelectMode.SelectRead)) { var args = new ClientConnectedEventArgs(socket, BufferSize); EndPoint remoteEndPoint = new IPEndPoint(0, 0); if (socket.Available == 0) { return; } args.ChannelBuffer.BytesTransferred = socket.ReceiveFrom(args.ChannelBuffer.Buffer, SocketFlags.None, ref remoteEndPoint); args.Channel.RemoteEndpoint = remoteEndPoint; if (args.ChannelBuffer.BytesTransferred > 0) { OnClientConnected(args); if (args.AllowConnect == false) { if (args.Response != null) { int sentBytes = 0; while ((sentBytes = args.Response.Read(sendBuffer, 0, sendBuffer.Length)) > 0) { socket.Send(sendBuffer, sentBytes, SocketFlags.None); } } logger.Debug("PACKET request from " + args.Channel.RemoteEndpoint.ToString() + " with channel id " + args.Channel.ChannelId.ToString() + " was denied access to connect."); } } } else { Thread.Sleep(10); } } catch (SocketException ex) { if (ex.ErrorCode == (int)SocketError.ConnectionReset) { return; } } catch (Exception ex) { HandleDisconnect(SocketError.SocketError, ex); } }
private void OnClientConnect(object sender, ClientConnectedEventArgs args) { SocketBuffer channelBuffer = args.ChannelBuffer; if (channelBuffer != null && args.Channel.IsConnected && channelBuffer.BytesTransferred >= Constants.SNTP_MIN_MESSAGE_SIZE && channelBuffer.BytesTransferred <= Constants.SNTP_MAX_MESSAGE_SIZE) { logger.Debug("PACKET request with channel id " + args.Channel.ChannelId.ToString() + " was received from " + args.Channel.RemoteEndpoint.ToString() + " and queued for processing..."); SntpMessageEventArgs messageArgs = new SntpMessageEventArgs(args.Channel, args.ChannelBuffer); OnSntpMessageReceived(this, messageArgs); ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessRequest), messageArgs); } }
/// <summary> /// A client has connected (nothing have been sent or received yet) /// </summary> /// <returns></returns> protected virtual void OnClientConnected(ClientConnectedEventArgs args) { ClientConnected(this, args); }