/// <summary> /// 异步接收信息或因超时导致框架自动关闭连接 /// </summary> /// <param name="func"></param> /// <param name="whenerror"></param> public virtual void RecieveAsync(Action <object> func, Action whenerror) { if (iswebsocket && socket.State == WebSocketState.Open) { string wsguid = ComFunc.nvl(_logic.CallContext_Parameter.ExtentionObj.websocket_uid); Task.Run(() => { try { if (socket.State == WebSocketState.Open) { object outobj = null; ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[2048]); var t = socket.ReceiveAsync(buffer, CancellationToken.None); t.Wait(); string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, t.Result.Count); if (GlobalCommon.ApplicationCache.Get(wsguid + "websocket_expiration") != null) { var expirationtime = (DateTime)GlobalCommon.ApplicationCache.Get(wsguid + "websocket_expiration"); expirationtime = DateTime.Now.AddMinutes(GlobalCommon.WebSocketCommon.MaxConnectionMinutes); } if (FrameDLRObject.IsJson(userMsg)) { outobj = FrameDLRObject.CreateInstance(userMsg); } else { outobj = userMsg; } if (func != null) { func.Invoke(outobj); } } } catch (Exception ex) { GlobalCommon.Logger.WriteLog(LoggerLevel.ERROR, "Exception happend in WebSockect RecieveSync Task Run:" + ex.Message + "\n" + ex.StackTrace); socket.CloseAsync(WebSocketCloseStatus.InternalServerError, "error", CancellationToken.None); if (whenerror != null) { whenerror.Invoke(); } } }); } }
/// <summary> /// 接收websockect发来的消息,该方法会阻断当前线程,直到消息发来或因超时导致框架自动关闭连接 /// 若因超时连接自动关闭则后续程序将无法处理 /// </summary> /// <returns></returns> public virtual object Recieve() { string wsguid = ComFunc.nvl(_logic.CallContext_Parameter.ExtentionObj.websocket_uid); object outobj = null; if (socket.State == WebSocketState.Open) { ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[4096]); var t = socket.ReceiveAsync(buffer, CancellationToken.None); t.Wait(); var result = t.Result; if (socket.State != WebSocketState.CloseReceived) { var bl = new List <byte>(); bl.AddRange(buffer.Array.Take(result.Count)); while (!result.EndOfMessage && result.MessageType != WebSocketMessageType.Close) { t = socket.ReceiveAsync(buffer, CancellationToken.None); t.Wait(); result = t.Result; bl.AddRange(buffer.Array.Take(result.Count)); } if (result.MessageType == WebSocketMessageType.Text) { string userMsg = Encoding.UTF8.GetString(bl.ToArray()); if (GlobalCommon.ApplicationCache.Get(wsguid + "websocket_expiration") != null) { var expirationtime = (DateTime)GlobalCommon.ApplicationCache.Get(wsguid + "websocket_expiration"); expirationtime = DateTime.Now.AddMinutes(GlobalCommon.WebSocketCommon.MaxConnectionMinutes); } if (FrameDLRObject.IsJson(userMsg)) { outobj = FrameDLRObject.CreateInstance(userMsg); } else { outobj = userMsg; } } else { outobj = bl.ToArray(); } } } return(outobj); }
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(); } }
private void ProcessWebSocketAsync(WebSocket arg) { TParameter tp = Activator.CreateInstance <TParameter>(); TData td = Activator.CreateInstance <TData>(); tp.ExtentionObj.websocket_uid = Guid.NewGuid().ToString(); _socket = arg; try { DateTime expirationtime = DateTime.Now.AddMinutes(Settings.WebSocket_Max_Connection_Live_Minute); BeforeProcess(tp, td); if (GlobalCommon.ApplicationCache.Get(tp.ExtentionObj.websocket_uid + "websocket_expiration") == null) { GlobalCommon.ApplicationCache.Set(tp.ExtentionObj.websocket_uid + "websocket_expiration", expirationtime, DateTime.Now.AddDays(1)); } CancellationTokenSource ct = new CancellationTokenSource(); 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>(); var t = _socket.ReceiveAsync(buffer, ct.Token); Task.WaitAll(t); WebSocketReceiveResult result = t.Result; if (_socket.State == WebSocketState.CloseReceived) { break; } bl.AddRange(buffer.Array.Take(result.Count)); while (!result.EndOfMessage) { t = _socket.ReceiveAsync(buffer, ct.Token); Task.WaitAll(t); result = t.Result; bl.AddRange(buffer.Array.Take(result.Count)); } //重置超时时间 expirationtime = DateTime.Now.AddMinutes(Settings.WebSocket_Max_Connection_Live_Minute); 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) { tp[DomainKey.POST_DATA, k] = jsondata.GetValue(k); } } else { tp[DomainKey.POST_DATA, "ws_data"] = userMsg; } } else { tp[DomainKey.POST_DATA, "ws_data"] = bl.ToArray(); } td.SetValue("websocket", _socket); InvokeAction(tp, td); AfterProcess(tp, td); } else { break; } } if (_socket.State == WebSocketState.Closed) { AfterProcess(tp, td); } } catch (Exception ex) { OnError(ex, tp, td); } finally { _socket.Abort(); } }