public void Auth(string sessionID, bool isConsole = false) { this.sessionID = sessionID; this.IsConsole = isConsole; ConcurrentDictionaryHelper <SocketSession> .Using(x => { x.AddOrUpdate(this.sessionID, this, (key, value) => { return(this); }); }); }
/// <summary> /// 接收到数据回调 /// </summary> /// <param name="ar"></param> private void AcceptReceiveDataCallback(IAsyncResult ar) { try { var bs = (byte[])ar.AsyncState; SocketError errorCode = SocketError.Success; var receivedNum = Client.Client.EndReceive(ar, out errorCode); ///如果客户端关闭,接受到数据长度为0 if (errorCode == SocketError.Success) { if (receivedNum == 0) { Client.Dispose(); ConcurrentDictionaryHelper <SocketSession> .Remove(this.sessionID); return; } receivedBytes.AddRange(bs.Take(receivedNum)); var message = Encoding.UTF8.GetString(receivedBytes.ToArray(), 0, receivedBytes.Count); AsyncHelper.Run(() => { LogHelper.WriteCustom(string.Format("{0}", message), @"SocketMessage\"); }); // 如果未结束,继续接收,完成后处理 if (receivedNum >= Client.ReceiveBufferSize && !message.EndsWith(Params.Socket_Text_Suffix, StringComparison.OrdinalIgnoreCase)) { Thread.Sleep(50); socketAccepted.Set(); return; } /// 判断数据是否符合格式要求 if (!message.IsNullOrEmpty() && message.EndsWith(Params.Socket_Text_Suffix, StringComparison.OrdinalIgnoreCase)) { OnRecevied(this, message.Substring(0, message.Length - 4)); } receivedBytes.Clear(); } } catch (Exception ex) { LogHelper.WriteException(ex); } socketAccepted.Set(); }
/// <summary> /// 开始接收数据 /// </summary> public void StartAccept() { Task.Run(() => { try { while (true) { socketAccepted.Reset(); var bs = new byte[Client.ReceiveBufferSize]; Client.Client.BeginReceive(bs, 0, bs.Length, SocketFlags.None, new AsyncCallback(AcceptReceiveDataCallback), bs); socketAccepted.WaitOne(); } } catch (Exception ex) { LogHelper.WriteException(ex); ConcurrentDictionaryHelper <SocketSession> .Remove(this.sessionID); } }); }
private void Send(string content, int resendNum, Action removeAction) { try { if (Stream.CanWrite) { var bytes = Encoding.UTF8.GetBytes(content + Params.Socket_Text_Suffix); Stream.Write(bytes, 0, bytes.Length); } } catch (Exception ex) { LogHelper.WriteException(ex); ConcurrentDictionaryHelper <SocketSession> .Remove(this.sessionID); if (removeAction != null) { removeAction(); } } }