public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { var total = data.Sum(d => d.Count); var payloadLength = context.PayloadLength; var text = Encoding.UTF8.GetString(data, total - payloadLength, payloadLength); return new WebSocketPackageInfo(text, ServiceProvider.StringParser); }
public override void OnCommandExecuted(IAppSession session, ICommand command) { var startTime = session.Items.GetValue<DateTime>("StartTime"); var ts = DateTime.Now.Subtract(startTime); if (ts.TotalSeconds > 5) { session.Logger.LogPerf(string.Format("A command '{0}' took {1} seconds!", command.Name, ts.ToString())); } }
public override void Initialize(IAppSession appSession) { base.Initialize(appSession); if (!SyncSend) { //Initialize SocketAsyncEventArgs for sending m_SocketEventArgSend = new SocketAsyncEventArgs(); m_SocketEventArgSend.Completed += new EventHandler<SocketAsyncEventArgs>(OnSendingCompleted); } }
public override void ResetSessionSecurity(IAppSession session, SslProtocols security) { ISocketSession socketSession; if (security == SslProtocols.None) socketSession = new AsyncSocketSession(session.SocketSession.Client, SaePool, true); else socketSession = new AsyncStreamSocketSession(session.SocketSession.Client, security, BufferManager, true); socketSession.Initialize(session); socketSession.Start(); }
public override void ResetSessionSecurity(IAppSession session, SslProtocols security) { ISocketSession socketSession; var socketAsyncProxy = ((IAsyncSocketSessionBase)session.SocketSession).SocketAsyncProxy; if (security == SslProtocols.None) socketSession = new AsyncSocketSession(session.SocketSession.Client, socketAsyncProxy, true); else socketSession = new AsyncStreamSocketSession(session.SocketSession.Client, security, socketAsyncProxy, true); socketSession.Initialize(session); socketSession.Start(); }
public override IWebSocketFragment Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool isReusableBuffer, out int left) { var webSocketSession = session as IWebSocketSession; int total = BufferSegments.Count + length; if (total == SecKey3Len) { byte[] key = new byte[SecKey3Len]; BufferSegments.CopyTo(key); Array.Copy(readBuffer, offset, key, BufferSegments.Count, length); webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = key; BufferSegments.ClearSegements(); left = 0; if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else if (total > SecKey3Len) { byte[] key = new byte[8]; BufferSegments.CopyTo(key); Array.Copy(readBuffer, offset, key, BufferSegments.Count, SecKey3Len - BufferSegments.Count); webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = key; BufferSegments.ClearSegements(); left = total - SecKey3Len; if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else { AddArraySegment(readBuffer, offset, length, isReusableBuffer); left = 0; NextRequestFilter = this; return null; } return null; }
public ReportAppService(INodeAppService nodeAppService, ApplicationDbContext dbcontext, ICommonConfiguration configuration, IAppSession appSession, UserManager <Domain.Entities.ApplicationUser> userManager, ILoggerFactory loggerFactory) : base(dbcontext, configuration, appSession, userManager, loggerFactory) { _nodeAppService = nodeAppService; }
public async Task TestCloseReason() { var hostConfigurator = new RegularHostConfigurator(); IAppSession session = null; using (var server = CreateSocketServerBuilder <TextPackageInfo, LinePipelineFilter>(hostConfigurator) .UseSessionHandler((s) => { session = s; return(new ValueTask()); }) .BuildAsServer()) { Assert.Equal("TestServer", server.Name); Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Started."); CloseReason closeReason = CloseReason.Unknown; var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(hostConfigurator.GetServerEndPoint()); OutputHelper.WriteLine("Connected."); await Task.Delay(1000); session.Closed += (s, e) => { closeReason = e.Reason; return(new ValueTask()); }; client.Shutdown(SocketShutdown.Both); client.Close(); await Task.Delay(1000); Assert.Equal(SessionState.Closed, session.State); Assert.Equal(CloseReason.RemoteClosing, closeReason); closeReason = CloseReason.Unknown; client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(hostConfigurator.GetServerEndPoint()); OutputHelper.WriteLine("Connected."); await Task.Delay(1000); session.Closed += (s, e) => { closeReason = e.Reason; return(new ValueTask()); }; await session.CloseAsync(CloseReason.LocalClosing); await Task.Delay(1000); Assert.Equal(SessionState.Closed, session.State); Assert.Equal(CloseReason.LocalClosing, closeReason); await server.StopAsync(); } }
/// <summary> /// Called when [command executing]. /// </summary> /// <param name="session">The session.</param> /// <param name="command">The command.</param> public abstract void OnCommandExecuting(IAppSession session, ICommand command);
public async ValueTask ExecuteAsync(IAppSession session, StringPackageInfo package) { await session.SendAsync(_encoder, "OK\r\n"); }
public override IWebSocketFragment FindCommandInfo(IAppSession session, byte[] readBuffer, int offset, int length, bool isReusableBuffer, out int left) { left = 0; int prevMatched = m_SearchState.Matched; var result = readBuffer.SearchMark(offset, length, m_SearchState); if (result < 0) { this.AddArraySegment(readBuffer, offset, length, isReusableBuffer); return(null); } int findLen = result - offset; string header = string.Empty; if (this.BufferSegments.Count > 0) { if (findLen > 0) { this.AddArraySegment(readBuffer, offset, findLen, false); header = this.BufferSegments.Decode(Encoding.UTF8); } else { header = this.BufferSegments.Decode(Encoding.UTF8, 0, this.BufferSegments.Count - prevMatched); } } else { header = Encoding.UTF8.GetString(readBuffer, offset, findLen); } var webSocketSession = session as IWebSocketSession; WebSocketServer.ParseHandshake(webSocketSession, new StringReader(header)); var secWebSocketKey1 = webSocketSession.Items.GetValue <string>(WebSocketConstant.SecWebSocketKey1, string.Empty); var secWebSocketKey2 = webSocketSession.Items.GetValue <string>(WebSocketConstant.SecWebSocketKey2, string.Empty); var secWebSocketVersion = webSocketSession.SecWebSocketVersion; left = length - findLen - (m_HeaderTerminator.Length - prevMatched); this.ClearBufferSegments(); if (string.IsNullOrEmpty(secWebSocketKey1) && string.IsNullOrEmpty(secWebSocketKey2)) { //draft-hixie-thewebsocketprotocol-75 if (Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) { return(HandshakeCommandInfo); } } else if ("6".Equals(secWebSocketVersion)) //draft-ietf-hybi-thewebsocketprotocol-06 { if (Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) { return(HandshakeCommandInfo); } } else { //draft-hixie-thewebsocketprotocol-76/draft-ietf-hybi-thewebsocketprotocol-00 //Read SecWebSocketKey3(8 bytes) if (left == SecKey3Len) { webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = readBuffer.CloneRange(offset + length - left, left); left = 0; if (Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) { return(HandshakeCommandInfo); } } else if (left > SecKey3Len) { webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = readBuffer.CloneRange(offset + length - left, 8); left -= 8; if (Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) { return(HandshakeCommandInfo); } } else { //left < 8 if (left > 0) { AddArraySegment(readBuffer, offset + length - left, left, isReusableBuffer); left = 0; } NextCommandReader = new WebSocketSecKey3Reader(this); return(null); } } return(null); }
public virtual void Initialize(IAppSession appSession) { AppSession = appSession; }
public async ValueTask ExecuteAsync(IAppSession session, StringPackageInfo package) { await session.SendAsync(Encoding.UTF8.GetBytes(session.SessionID + "\r\n")); }
public override void OnCommandExecuted(IAppSession session, ICommand command) { Interlocked.Increment(ref m_Total); }
public override IWebSocketFragment Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool isReusableBuffer, out int left) { left = 0; int prevMatched = m_SearchState.Matched; var result = readBuffer.SearchMark(offset, length, m_SearchState); if (result < 0) { this.AddArraySegment(readBuffer, offset, length, isReusableBuffer); return null; } int findLen = result - offset; string header = string.Empty; if (this.BufferSegments.Count > 0) { if (findLen > 0) { this.AddArraySegment(readBuffer, offset, findLen, false); header = this.BufferSegments.Decode(Encoding.UTF8); } else { header = this.BufferSegments.Decode(Encoding.UTF8, 0, this.BufferSegments.Count - prevMatched); } } else { header = Encoding.UTF8.GetString(readBuffer, offset, findLen); } var webSocketSession = session as IWebSocketSession; try { WebSocketServer.ParseHandshake(webSocketSession, new StringReader(header)); } catch (Exception e) { session.Logger.Error("Failed to parse handshake!" + Environment.NewLine + header, e); session.Close(CloseReason.ProtocolError); return null; } var secWebSocketKey1 = webSocketSession.Items.GetValue<string>(WebSocketConstant.SecWebSocketKey1, string.Empty); var secWebSocketKey2 = webSocketSession.Items.GetValue<string>(WebSocketConstant.SecWebSocketKey2, string.Empty); var secWebSocketVersion = webSocketSession.SecWebSocketVersion; left = length - findLen - (m_HeaderTerminator.Length - prevMatched); this.ClearBufferSegments(); if (string.IsNullOrEmpty(secWebSocketKey1) && string.IsNullOrEmpty(secWebSocketKey2)) { //draft-hixie-thewebsocketprotocol-75 if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else if ("6".Equals(secWebSocketVersion)) //draft-ietf-hybi-thewebsocketprotocol-06 { if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else { //draft-hixie-thewebsocketprotocol-76/draft-ietf-hybi-thewebsocketprotocol-00 //Read SecWebSocketKey3(8 bytes) if (left == SecKey3Len) { webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = readBuffer.CloneRange(offset + length - left, left); left = 0; if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else if (left > SecKey3Len) { webSocketSession.Items[WebSocketConstant.SecWebSocketKey3] = readBuffer.CloneRange(offset + length - left, 8); left -= 8; if(Handshake(webSocketSession.AppServer.WebSocketProtocolProcessor, webSocketSession)) return HandshakeRequestInfo; } else { //left < 8 if (left > 0) { AddArraySegment(readBuffer, offset + length - left, left, isReusableBuffer); left = 0; } NextRequestFilter = new WebSocketSecKey3RequestFilter(this); return null; } } return null; }
public async Task Handle(IAppSession session, WebSocketPackage package) { var websocketSession = session as WebSocketSession; if (package.OpCode == OpCode.Handshake) { // handshake failure if (!await HandleHandshake(session, package)) { return; } websocketSession.Handshaked = true; return; } if (!websocketSession.Handshaked) { // not pass handshake but receive data package now // impossible routine return; } if (package.OpCode == OpCode.Close) { if (websocketSession.CloseStatus == null) { var closeStatus = GetCloseStatusFromPackage(package); websocketSession.CloseStatus = closeStatus; var message = new WebSocketMessage(); message.OpCode = OpCode.Close; message.Data = package.Data; await websocketSession.SendAsync(message); } //After both sending and receiving a Close message, the server MUST close the underlying TCP connection immediately websocketSession.CloseWithoutHandshake(); return; } // application command var websocketCommandMiddleware = _websocketCommandMiddleware; if (websocketCommandMiddleware != null) { await websocketCommandMiddleware.Handle(session, package); return; } var packageHandleDelegate = _packageHandlerDelegate; if (packageHandleDelegate != null) { await packageHandleDelegate(websocketSession, package); } }
public SystemAppService(INodeAppService nodeAppService, IMessageAppService messageAppService, ISchedulerAppService schedulerAppService, ApplicationDbContext dbcontext, ICommonConfiguration configuration, IAppSession appSession, UserManager <ApplicationUser> userManager, ILoggerFactory loggerFactory) : base(dbcontext, configuration, appSession, userManager, loggerFactory) { _schedulerAppService = schedulerAppService; _nodeAppService = nodeAppService; _messageAppService = messageAppService; }
public WebSocketContext(IAppSession session, HttpHeaderInfo request) { Session = session; HandshakeRequest = request; }
public IReceiveFilter <AuthRequest> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint) { return(new AuthComposer(requestFactory, ((AuthServer)appServer).RegisteredCommands)); }
public WebSocketContext(IAppSession session, HttpHeaderInfo request) { Session = session; HandshakeRequest = request; }
private async ValueTask ExecuteAsyncWithFilter(IAppSession session, TPackageInfo package) { var context = new CommandExecutingContext(); context.Package = package; context.Session = session; var command = AsyncCommand != null ? (AsyncCommand as ICommand) : (Command as ICommand); if (command is ICommandWrap commandWrap) { command = commandWrap.InnerCommand; } context.CurrentCommand = command; var filters = Filters; var continued = true; for (var i = 0; i < filters.Count; i++) { var f = filters[i]; if (f is AsyncCommandFilterAttribute asyncCommandFilter) { continued = await asyncCommandFilter.OnCommandExecutingAsync(context); } else if (f is CommandFilterAttribute commandFilter) { continued = commandFilter.OnCommandExecuting(context); } if (!continued) { break; } } if (!continued) { return; } try { var appSession = (TAppSession)session; var asyncCommand = AsyncCommand; if (asyncCommand != null) { await asyncCommand.ExecuteAsync(appSession, package); } else { Command.Execute(appSession, package); } } catch (Exception e) { context.Exception = e; } finally { for (var i = 0; i < filters.Count; i++) { var f = filters[i]; if (f is AsyncCommandFilterAttribute asyncCommandFilter) { await asyncCommandFilter.OnCommandExecutedAsync(context); } else if (f is CommandFilterAttribute commandFilter) { commandFilter.OnCommandExecuted(context); } } } }
public void AcceptNewSession(IAppSession session) { m_OpenHandshakePendingQueue.Enqueue(session); }
public override IWebSocketFragment FindCommandInfo(IAppSession session, byte[] readBuffer, int offset, int length, bool isReusableBuffer, out int left) { left = 0; var skipByteCount = 0; if (!m_Type.HasValue) { byte startByte = readBuffer[offset]; skipByteCount = 1; m_Type = startByte; } //0xxxxxxx: Collect protocol data by end mark if ((m_Type.Value & 0x80) == 0x00) { byte lookForByte = 0xFF; int i; for (i = offset + skipByteCount; i < offset + length; i++) { if (readBuffer[i] == lookForByte) { left = length - (i - offset + 1); if (BufferSegments.Count <= 0) { var commandInfo = new PlainFragment(Encoding.UTF8.GetString(readBuffer, offset + skipByteCount, i - offset - skipByteCount)); Reset(); return commandInfo; } else { AddArraySegment(readBuffer, offset + skipByteCount, i - offset - skipByteCount, false); var commandInfo = new PlainFragment(BufferSegments.Decode(Encoding.UTF8)); Reset(); return commandInfo; } } } AddArraySegment(readBuffer, offset + skipByteCount, length - skipByteCount, isReusableBuffer); return null; } else//10000000: Collect protocol data by length { while (!m_Length.HasValue) { if (length <= skipByteCount) { //No data to read return null; } byte lengthByte = readBuffer[skipByteCount]; //Closing handshake if (lengthByte == 0x00 && m_Type.Value == m_ClosingHandshakeType) { session.Close(CloseReason.ClientClosing); return null; } int thisLength = (int)(lengthByte & 0x7F); m_TempLength = m_TempLength * 128 + thisLength; skipByteCount++; if ((lengthByte & 0x80) != 0x80) { m_Length = m_TempLength; break; } } int requiredSize = m_Length.Value - BufferSegments.Count; int leftSize = length - skipByteCount; if (leftSize < requiredSize) { AddArraySegment(readBuffer, skipByteCount, length - skipByteCount, isReusableBuffer); return null; } else { left = leftSize - requiredSize; if (BufferSegments.Count <= 0) { var commandInfo = new PlainFragment(Encoding.UTF8.GetString(readBuffer, offset + skipByteCount, requiredSize)); Reset(); return commandInfo; } else { AddArraySegment(readBuffer, offset + skipByteCount, requiredSize, false); var commandInfo = new PlainFragment(BufferSegments.Decode(Encoding.UTF8)); Reset(); return commandInfo; } } } }
public IRequestFilter <MyUdpRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint) { return(new MyRequestFilter()); }
/// <summary> /// Initializes a new instance of the <see cref="CommandExecutingContext"/> class. /// </summary> /// <param name="session">The session.</param> /// <param name="requestInfo">The request info.</param> /// <param name="command">The command.</param> public CommandExecutingContext(IAppSession session, IRequestInfo requestInfo, ICommand command) { Session = session; RequestInfo = requestInfo; CurrentCommand = command; }
/// <summary> /// Creates the filter. /// </summary> /// <param name="appServer">The app server.</param> /// <param name="appSession">The app session.</param> /// <param name="remoteEndPoint">The remote end point.</param> /// <returns></returns> public IReceiveFilter <IWebSocketFragment> CreateFilter(IAppServer appServer, IAppSession appSession, System.Net.IPEndPoint remoteEndPoint) { return(new WebSocketHeaderReceiveFilter((IWebSocketSession)appSession)); }
private bool RegisterSession(IAppSession appSession) { if (AppServer.RegisterSession(appSession)) return true; appSession.SocketSession.Close(CloseReason.InternalError); return false; }
/// <summary> /// Initializes a new instance of the <see cref="CommandExecutingContext" /> class. /// </summary> /// <param name="session">The session.</param> /// <param name="requestInfo">The request info.</param> /// <param name="command">The command.</param> public void Initialize(IAppSession session, IRequestInfo requestInfo, ICommand command) { Session = session; RequestInfo = requestInfo; CurrentCommand = command; }
protected void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started _appSession = new AppSession(); }
public void Handshake(IAppSession session, HttpHeaderInfo head) { throw new NotImplementedException(); }
bool IAppServer.RemoveSession(IAppSession appSession) { return(_sessionManager.RemoveSession(appSession)); }
private async Task OnlinedNotice(IAppSession session) { var availableRoomsIds = _roomManager.GetRoomIds().Select(id => id.ToString()); var availableRoomIdText = "Select One Room Into: \r\n" + string.Join('\t', availableRoomsIds) + "\r\n"; await session.Channel.SendAsync(Encoding.UTF8.GetBytes(availableRoomIdText)); }
void IReceiveFilterInitializer.Initialize(IAppServer appServer, IAppSession session) { m_OrigOffset = session.SocketSession.OrigReceiveOffset; }
public override async ValueTask Handle(IAppSession session, WebSocketPackage package) { await _commandMiddleware.Handle(session, package); }
public abstract ValueTask HandlePackage(IAppSession session, TPackageInfo package);
public async ValueTask Handle(IAppSession session, WebSocketPackage package) { var websocketSession = session as WebSocketSession; if (package.OpCode == OpCode.Handshake) { websocketSession.HttpHeader = package.HttpHeader; // handshake failure if (!(await HandleHandshake(websocketSession, package))) { websocketSession.CloseWithoutHandshake(); return; } websocketSession.Handshaked = true; var subProtocol = package.HttpHeader.Items["Sec-WebSocket-Protocol"]; if (!string.IsNullOrEmpty(subProtocol)) { var subProtocols = subProtocol.Split(','); for (var i = 0; i < subProtocols.Length; i++) { subProtocols[i] = subProtocols[i].Trim(); } var subProtocolSelector = _subProtocolSelector; if (subProtocolSelector != null) { var subProtocolSelected = await subProtocolSelector.Select(subProtocols, package.HttpHeader); if (!string.IsNullOrEmpty(subProtocolSelected)) { websocketSession.SubProtocol = subProtocolSelected; } } } await(session.Server as WebSocketService).OnSessionHandshakeCompleted(websocketSession); return; } if (!websocketSession.Handshaked) { // not pass handshake but receive data package now // impossible routine return; } if (package.OpCode == OpCode.Close) { if (websocketSession.CloseStatus == null) { var closeStatus = GetCloseStatusFromPackage(package); websocketSession.CloseStatus = closeStatus; var message = new WebSocketMessage(); message.OpCode = OpCode.Close; message.Data = package.Data; try { await websocketSession.SendAsync(message); } catch (InvalidOperationException) { // support the case the client close the connection right after it send the close handshake } } else { websocketSession.CloseWithoutHandshake(); } return; } else if (package.OpCode == OpCode.Ping) { var message = new WebSocketMessage(); message.OpCode = OpCode.Pong; message.Data = package.Data; await websocketSession.SendAsync(message); return; } // application command var websocketCommandMiddleware = _websocketCommandMiddleware; if (websocketCommandMiddleware != null) { await websocketCommandMiddleware.Handle(session, package); return; } var packageHandleDelegate = _packageHandlerDelegate; if (packageHandleDelegate != null) { await packageHandleDelegate(websocketSession, package); } }
/// <summary> /// Initializes a new instance of the <see cref="CommandExecutingContext" /> class. /// </summary> /// <param name="session">The session.</param> /// <param name="requestInfo">The request info.</param> /// <param name="command">The command.</param> public void Initialize(IAppSession session, IRequestInfo requestInfo, ICommand command) { Session = session; RequestInfo = requestInfo; CurrentCommand = command; }
public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { throw new NotImplementedException(); }
public abstract WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data);
public IReceiveFilter <BinaryRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint) { return(new MsgPackReceiveFilter()); }
public override void OnCommandExecuting(IAppSession session, ICommand command) { }
/// <summary> /// Creates the Receive filter. /// </summary> /// <param name="appServer">The app server.</param> /// <param name="appSession">The app session.</param> /// <param name="remoteEndPoint">The remote end point.</param> /// <returns> /// the new created request filer assosiated with this socketSession /// </returns> public virtual IReceiveFilter <StringRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint) { return(new TerminatorReceiveFilter(appSession, m_Terminator, m_Encoding, m_RequestInfoParser)); }
/// <summary> /// 处理 /// </summary> /// <param name="session">Session</param> /// <param name="package">WebSocket包</param> /// <returns></returns> public async ValueTask Handle(IAppSession session, WebSocketPackage package) { var websocketSession = session as WebSocketSession; if (package.OpCode == OpCode.Handshake) { websocketSession.HttpHeader = package.HttpHeader; // handshake failure if (!(await HandleHandshake(websocketSession, package))) { websocketSession.CloseWithoutHandshake(); return; } websocketSession.Handshaked = true; await _websocketServerMiddleware.HandleSessionHandshakeCompleted(websocketSession); return; } if (!websocketSession.Handshaked) { // not pass handshake but receive data package now // impossible routine return; } if (package.OpCode == OpCode.Close) { if (websocketSession.CloseStatus == null) { var closeStatus = GetCloseStatusFromPackage(package); websocketSession.CloseStatus = closeStatus; try { await websocketSession.SendAsync(package); } catch (InvalidOperationException) { // support the case the client close the connection right after it send the close handshake } } else { websocketSession.CloseWithoutHandshake(); } return; } else if (package.OpCode == OpCode.Ping) { package.OpCode = OpCode.Pong; await websocketSession.SendAsync(package); return; } var protocolHandler = websocketSession.SubProtocolHandler; if (protocolHandler != null) { await protocolHandler.Handle(session, package); return; } // application command var websocketCommandMiddleware = _websocketCommandMiddleware; if (websocketCommandMiddleware != null) { await websocketCommandMiddleware.Handle(session, package); return; } var packageHandleDelegate = _packageHandlerDelegate; if (packageHandleDelegate != null) { await packageHandleDelegate(websocketSession, package); } }
public NodeHeartbeatAppService(IMessageAppService messageAppService, ApplicationDbContext dbcontext, ICommonConfiguration configuration, IAppSession appSession, UserManager <ApplicationUser> userManager, ILoggerFactory loggerFactory) : base(dbcontext, configuration, appSession, userManager, loggerFactory) { _messageAppService = messageAppService; }
public virtual void Initialize(IAppSession appSession) { AppSession = appSession; Config = appSession.Config; SyncSend = Config.SyncSend; m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool; SendingQueue queue; if (m_SendingQueuePool.TryGet(out queue)) { m_SendingQueue = queue; queue.StartEnqueue(); } }
public override WebSocketPackageInfo Handle(IAppSession session, WebSocketContext context, IList<ArraySegment<byte>> data) { return new WebSocketPackageInfo(data, ServiceProvider.BinaryDataParser, ServiceProvider.StringParser); }
public virtual void Initialize(IAppSession appSession) { AppSession = appSession; DataProcessor = appSession.CreatePipelineProcessor(); Config = appSession.Config; SyncSend = Config.SyncSend; m_SendingQueuePool = ((SocketServerBase)((ISocketServerAccessor)appSession.AppServer).SocketServer).SendingQueuePool; SendingQueue queue = m_SendingQueuePool.Get(); m_SendingQueue = queue; queue.StartEnqueue(); }
public override void OnCommandExecuting(IAppSession session, ICommand command) { session.Items["StartTime"] = DateTime.Now; }
public virtual void Initialize(IAppSession appSession) { AppSession = appSession; Config = appSession.Config; SyncSend = Config.SyncSend; }
public void AcceptNewSession(IAppSession session) { m_OpenHandshakePendingQueue.Enqueue(session); }
public async ValueTask ExecuteAsync(IAppSession session, MQTTPacket package) { var PubAckPacket = package as PubAckPacket; await session.SendAsync(PubAckPacket.PacketData); }
/// <summary> /// 处理握手 /// </summary> /// <param name="session">Session</param> /// <param name="p">WebSocket包</param> /// <returns></returns> private async ValueTask <bool> HandleHandshake(IAppSession session, WebSocketPackage p) { const string requiredVersion = "13"; var version = p.HttpHeader.Items[WebSocketConstant.SecWebSocketVersion]; if (!requiredVersion.Equals(version)) { return(false); } var secWebSocketKey = p.HttpHeader.Items[WebSocketConstant.SecWebSocketKey]; if (string.IsNullOrEmpty(secWebSocketKey)) { return(false); } var handshakeValidator = _handshakeOptions?.HandshakeValidator; if (handshakeValidator != null) { if (!await handshakeValidator(session as WebSocketSession, p)) { return(false); } } var ws = session as WebSocketSession; var strProtocols = p.HttpHeader.Items[WebSocketConstant.SecWebSocketProtocol]; var selectedProtocol = string.Empty; if (!string.IsNullOrEmpty(strProtocols)) { if (SelectSubProtocol(strProtocols, out string proto, out ISubProtocolHandler handler)) { ws.SubProtocol = proto; ws.SubProtocolHandler = handler; selectedProtocol = proto; } } var selectedExtensionHeadItems = SelectExtensions(p.HttpHeader.Items[WebSocketConstant.SecWebSocketExtensions], out List <IWebSocketExtension> extensions); if (selectedExtensionHeadItems != null && selectedExtensionHeadItems.Count > 0) { var pipeChannel = session.Channel as IPipeChannel; pipeChannel.PipelineFilter.Context = new WebSocketPipelineFilterContext { Extensions = extensions }; ws.MessageEncoder = new WebSocketEncoder { Extensions = extensions }; } else { ws.MessageEncoder = _defaultMessageEncoder; } string secKeyAccept = string.Empty; try { secKeyAccept = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(secWebSocketKey + _magic))); } catch (Exception) { return(false); } var encoding = _textEncoding; await session.Channel.SendAsync((writer) => { writer.Write(WebSocketConstant.ResponseHeadLine10, encoding); writer.Write(WebSocketConstant.ResponseUpgradeLine, encoding); writer.Write(WebSocketConstant.ResponseConnectionLine, encoding); writer.Write(string.Format(WebSocketConstant.ResponseAcceptLine, secKeyAccept), encoding); if (!string.IsNullOrEmpty(selectedProtocol)) { writer.Write(string.Format(WebSocketConstant.ResponseProtocolLine, selectedProtocol), encoding); } WriteExtensions(writer, encoding, selectedExtensionHeadItems); writer.Write("\r\n", encoding); writer.FlushAsync().GetAwaiter().GetResult(); }); return(true); }
public static WebSocketContext Get(IAppSession session) { object context; if (!session.Items.TryGetValue(c_WebSocketContextKey, out context)) return null; return context as WebSocketContext; }
public ValueTask ExecuteAsync(IAppSession session, MQTTPacket package) { throw new System.NotImplementedException(); }
public abstract void ResetSessionSecurity(IAppSession session, SslProtocols security);
public IReceiveFilter <StringPackageInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint) { var websocketContext = new WebSocketContext(appSession, appServer.BufferManager); return(new WebSocketHandshakeReceiveFilter(websocketContext)); }
public abstract void ResetSessionSecurity(IAppSession session, SslProtocols security);
protected void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. if (_appSession != null) _appSession.Dispose(); _appSession = null; }