/// <summary> /// Process the request asynchronously. /// </summary> /// <param name="webSocketContext">The web socket context.</param> /// <returns>The task to execute.</returns> private async Task ProcessWebSocketRequestAsync(System.Web.WebSockets.AspNetWebSocketContext webSocketContext) { await Nequeo.Threading.AsyncOperationResult <bool> . RunTask(() => { // Process the request. WebSocketContext(webSocketContext); }); }
/// <summary> /// Called when a new web socket connection has been established. /// </summary> /// <param name="webSocketContext">The web socket context.</param> public abstract void WebSocketContext(System.Web.WebSockets.AspNetWebSocketContext webSocketContext);
/// <summary> /// Process the request asynchronously. /// </summary> /// <param name="webSocketContext">The web socket context.</param> /// <returns>The task to execute.</returns> private Task ProcessWebSocketRequestAsync(System.Web.WebSockets.AspNetWebSocketContext webSocketContext) { // Process the request. return(WebSocketContext(webSocketContext)); }
private async Task ProcessWebSocket(System.Web.WebSockets.AspNetWebSocketContext arg) { WP p = Activator.CreateInstance <WP>(); WD d = Activator.CreateInstance <WD>(); p.ExtentionObj.websocket_uid = Guid.NewGuid().ToString(); WebSocket socket = arg.WebSocket; _socket = socket; try { DateTime expirationtime = DateTime.Now.AddMinutes(GlobalCommon.WebSocketCommon.MaxConnectionMinutes); Init(_context, p, d); if (GlobalCommon.ApplicationCache.Get(p.ExtentionObj.websocket_uid + "websocket_expiration") == null) { GlobalCommon.ApplicationCache.Set(p.ExtentionObj.websocket_uid + "websocket_expiration", expirationtime, DateTime.Now.AddDays(1)); } CancellationTokenSource ct = new CancellationTokenSource(); //Task.Factory.StartNew(() => //{ // try // { // var isend = false; // while (!isend) // { // expirationtime = (DateTime)GlobalCommon.ApplicationCache.Get(p.ExtentionObj.websocket_uid + "websocket_expiration"); // if (DateTime.Now > expirationtime) // { // ct.Cancel(); // isend = true; // AfterProcess(_context, p, d); // break; // } // Thread.Sleep(30 * 1000); // } // } // catch (Exception ex) // { // OnError(ex, p, d); // } //}); while (true) { if (socket.State == WebSocketState.Open) { //设置websockect能接受的数据大小不受限制,但单次接收的数据最多只有4088个byte,websocket对于大数据会分多段传送为,因此buffer定为4K ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[4096]); List <byte> bl = new List <byte>(); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, ct.Token); if (socket.State == WebSocketState.CloseReceived) { break; } bl.AddRange(buffer.Array.Take(result.Count)); while (!result.EndOfMessage) { result = await socket.ReceiveAsync(buffer, ct.Token); bl.AddRange(buffer.Array.Take(result.Count)); } //重置超时时间 expirationtime = DateTime.Now.AddMinutes(GlobalCommon.WebSocketCommon.MaxConnectionMinutes); if (result.MessageType == WebSocketMessageType.Text) { string userMsg = Encoding.UTF8.GetString(bl.ToArray()); if (FrameDLRObject.IsJson(userMsg)) { FrameDLRObject jsondata = FrameDLRObject.CreateInstance(userMsg); foreach (var k in jsondata.Keys) { p[DomainKey.POST_DATA, k] = jsondata.GetValue(k); } } else { p[DomainKey.POST_DATA, "ws_data"] = userMsg; } } else { p[DomainKey.POST_DATA, "ws_data"] = bl.ToArray(); } d.SetValue("websocket", socket); StepStart(p, d); AfterProcess(_context, p, d); } else { break; } } if (socket.State == WebSocketState.Closed) { AfterProcess(_context, p, d); } } catch (Exception ex) { OnError(ex, p, d); } finally { socket.Abort(); } }
public static string CreatePlayerKey(this System.Web.WebSockets.AspNetWebSocketContext _this, string optionalString) { return(_this.UserAgent + "/" + _this.UserHostAddress + "/" + _this.RequestUri + "/" + optionalString); }
/// <summary> /// On web socket context. /// </summary> /// <param name="webSocketContext">The asp net web socket context.</param> private async void OnChatWebSocketContext(System.Web.WebSockets.AspNetWebSocketContext context) { WebSocket webSocket = null; Nequeo.Net.WebSockets.WebSocketMember member = null; Nequeo.Collections.CircularBuffer <byte> requestBuffer = null; Nequeo.IO.Stream.StreamBufferBase requestStream = null; try { // Get the current web socket. webSocket = context.WebSocket; // Create the web socket member and // add to the member collection. member = new Nequeo.Net.WebSockets.WebSocketMember(webSocket); AddMember(member); // Holds the receive data. bool hasBeenFound = false; byte[] store = new byte[0]; byte[] receiveBuffer = new byte[READ_BUFFER_SIZE]; // Create the stream buffers. requestBuffer = new Collections.CircularBuffer <byte>(base.RequestBufferCapacity); requestStream = new Nequeo.IO.Stream.StreamBufferBase(requestBuffer); requestBuffer.RemoveItemsWritten = true; // Create the current chat state. Chat.ChatWebSocketState chatState = new Chat.ChatWebSocketState() { Member = member, RequestStream = requestStream, WebSocket = webSocket }; CancellationTokenSource receiveCancelToken = new CancellationTokenSource(); // While the WebSocket connection remains open run a // simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // Receive the next set of data. ArraySegment <byte> arrayBuffer = new ArraySegment <byte>(receiveBuffer); WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arrayBuffer, receiveCancelToken.Token); // Assign the member properties. member.ReceiveResult = receiveResult; member.TimeoutTime = DateTime.Now; requestStream.Write(receiveBuffer, 0, receiveResult.Count); // If the connection has been closed. if (receiveResult.MessageType == WebSocketMessageType.Close) { // Close the connection. member.Close(); break; } else { // Store the data. byte[] temp = null; if (!hasBeenFound) { temp = store.CombineParallel(receiveBuffer); // Find the end of the data. hasBeenFound = Nequeo.Net.Utility.IsParse2CRLF(temp); // Store the data until the end. store = temp; temp = null; } else { // If this is the end of the message. if (receiveResult.EndOfMessage) { // Clear the store. store = null; store = new byte[0]; hasBeenFound = false; string resource = ""; // Get the request headers. List <Nequeo.Model.NameValue> headers = base.ParseHeaders(requestStream, out resource, base.HeaderTimeout); // All headers have been found. if (headers != null) { // Get the execution member. // Set the calling member. string executionMember = headers.First(m => m.Name.ToUpper().Contains("MEMBER")).Value; string actionName = headers.First(m => m.Name.ToUpper().Contains("ACTIONNAME")).Value; // Assign the values. chatState.Headers = headers; chatState.ExecutionMember = executionMember; chatState.ErrorCode = new Exceptions.ErrorCodeException("OK", 200); try { // Validate the current user token. bool isTokenValid = ValidateToken(chatState); } catch (Exceptions.ErrorCodeException exc) { // Get the error code. chatState.ErrorCode = exc; } catch (Exception ex) { // Internal error. chatState.ErrorCode = new Exceptions.ErrorCodeException(ex.Message, 500); } // Send a message back to the client indicating that // the message was recivied and was sent. await webSocket.SendAsync(new ArraySegment <byte>( CreateResponse(chatState.ErrorCode.ErrorCode, true, executionMember, actionName, chatState.ErrorCode.Message)), WebSocketMessageType.Binary, true, CancellationToken.None); } } } } } // Cancel the receive request. if (webSocket.State != WebSocketState.Open) { receiveCancelToken.Cancel(); } } catch { } finally { // If a member context exists. if (member != null) { try { // Remove the member context // from the collection. RemoveMember(member); } catch { } member = null; } // Clean up by disposing the WebSocket. if (webSocket != null) { webSocket.Dispose(); } if (requestBuffer != null) { requestBuffer.Dispose(); } if (requestStream != null) { requestStream.Dispose(); } if (_communication != null) { try { // Remove the client from the communication service. _communication.RemoveClient(member.UniqueIdentifier, base.ServiceName, _machineName, null, actionName: member.UniqueIdentifier); } catch { } } } }
/// <summary> /// On web socket context. /// </summary> /// <param name="webSocketContext">The asp net web socket context.</param> public override void WebSocketContext(System.Web.WebSockets.AspNetWebSocketContext webSocketContext) { OnChatWebSocketContext(webSocketContext); }