private static GameSession OnCreate(Guid keyCode, params object[] args) { GameSession session; if (args.Length == 1) { session = new GameSession(keyCode, args[0]); } else if (args.Length == 2 && args[0] is ExSocket) { ExSocket socket = args[0] as ExSocket; var appServer = args[1] as ISocket; session = new GameSession(keyCode, socket, appServer); } else if (args.Length == 3) { var ssid = args[0] as string; var upAgentGuid = (Guid)args[1]; var userHostAddress = args[2] as string; session = new GameSession(keyCode, ssid, upAgentGuid, userHostAddress); } else { throw new ArgumentOutOfRangeException("param is error"); } _globalSession[keyCode] = session; OnChangedSave(); return(session); }
public static bool IsBServiceAlive(string strServer, System.Int32 intPort) { // Create a TcpClient. // Note, for this client to work you need to have a TcpServer // connected to the same address as specified by the server, port // combination. System.Diagnostics.Debug.WriteLine("IsBServiceAlive. Inicio: " + System.DateTime.Now); System.Net.Sockets.TcpClient client = new TcpClient(); try { client.NoDelay = true; client.Connect(strServer, intPort); client.Close(); return(true); } catch (System.Net.Sockets.SocketException ExSocket) { System.Diagnostics.Debug.WriteLine(ExSocket.ToString()); return(false); } catch (System.Exception Ex) { System.Diagnostics.Debug.WriteLine(Ex.ToString()); return(false); } finally { System.Diagnostics.Debug.WriteLine("IsBServiceAlive. Fin: " + System.DateTime.Now); // Close everything. client.Close(); } }
public ClientSessionImpl(SocketListener socketListener, IHostContext appContext, ExSocket exSocket, object command) { _socketListener = socketListener; _appContext = appContext; _exSocket = exSocket; _command = command; }
/// <summary> /// Recover session /// </summary> /// <param name="session"></param> /// <param name="newSessionKey"></param> /// <param name="socket"></param> /// <param name="appServer"></param> /// <returns></returns> public static void Recover(GameSession session, Guid newSessionKey, ExSocket socket, ISocket appServer) { var newSession = Get(newSessionKey); if (session != null && newSession != null && session != newSession) { try { session._exSocket.Close(); } catch { } //modify socket's keycod not found reason socket.Reset(session.KeyCode); session._exSocket = socket; session.AppServer = appServer; GameSession temp; if (_globalSession.TryRemove(newSessionKey, out temp)) { OnChangedSave(); } } }
private static GameSession OnCreate(Guid keyCode, params object[] args) { GameSession session; if (args.Length == 0) { session = new GameSession(keyCode, null); } else if (args.Length == 1) { session = new GameSession(keyCode, args[0]); } else if (args.Length == 2 && args[0] is ExSocket) { ExSocket socket = args[0] as ExSocket; var appServer = args[1] as ISocket; session = new GameSession(keyCode, socket, appServer); } else { throw new ArgumentOutOfRangeException("param is error"); } _globalSession[keyCode] = session; return(session); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="handshakeData"></param> /// <returns></returns> protected override bool ResponseHandshake(ExSocket socket, HandshakeData handshakeData) { string secKey1; string secKey2; byte[] secKey3; if (handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey1, out secKey1) && handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey2, out secKey2) && handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey3, out secKey3)) { //The minimum version support StringBuilder response = new StringBuilder(); response.AppendLine(HandshakeHeadKeys.RespHead_00); response.AppendLine(HandshakeHeadKeys.RespUpgrade00); response.AppendLine(HandshakeHeadKeys.RespConnection); string origin; if (handshakeData.ParamItems.TryGet(HandshakeHeadKeys.Origin, out origin)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespOriginLine, origin)); } response.AppendLine(string.Format(HandshakeHeadKeys.SecLocation, handshakeData.UriSchema, handshakeData.Host, handshakeData.UrlPath)); if (!string.IsNullOrEmpty(handshakeData.Protocol)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespProtocol, handshakeData.Protocol)); } response.AppendLine(); Handler.SendMessage(socket, response.ToString(), Encoding); //Encrypt message byte[] securityKey = GetResponseSecurityKey(secKey1, secKey2, secKey3); Handler.SendMessage(socket, securityKey); return(true); } return(false); }
internal bool SendAsync(ExSocket socket, byte[] buffer) { if (socket.DirectSendOrEnqueue(buffer)) { TryDequeueAndPostSend(socket, null); return(true); } return(false); }
private void socketLintener_OnClosedStatus(ExSocket socket, int closeStatusCode) { try { OnClosedStatus(socket, closeStatusCode); } catch (Exception err) { TraceLog.WriteError("OnPong error:{0}", err); } }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { if (opCode == OpCode.Close) { return(ClosingBytes); } byte[] buffer = new byte[count + 2]; buffer[0] = StartByte; Buffer.BlockCopy(data, offset, buffer, 1, count); buffer[count + 1] = EndByte; return(buffer); }
/// <summary> /// Recover session /// </summary> /// <param name="session"></param> /// <param name="newSessionKey"></param> /// <param name="socket"></param> /// <param name="sendCallback"></param> /// <returns></returns> public static void Recover(GameSession session, Guid newSessionKey, ExSocket socket, Action <ExSocket, byte[], int, int> sendCallback) { var newSession = Get(newSessionKey); if (session != null && newSession != null && session != newSession) { session._exSocket = socket; session._sendCallback = sendCallback; GameSession temp; _globalSession.TryRemove(newSessionKey, out temp); } }
internal void InitSocket(ExSocket exSocket, ISocket appServer) { _exSocket = exSocket; if (_exSocket != null) { _remoteAddress = _exSocket.RemoteEndPoint.ToNotNullString(); } AppServer = appServer; if (User != null) { //update userid with sid. _userHash[UserId] = KeyCode; } }
private void ProcessPackage(object state) { var package = (RequestPackage)state; var param = package.Param; var session = package.Session; var ssid = package.SSID; var actionid = int.Parse(param["actionid"]); if (actionid == 1) {// 客户端tcp心跳包 session.LastActivityTime = DateTime.Now; session.ExitSession(); Interlocked.Decrement(ref runningNum); return; } try { bool needWrite; //var data = ActionFactory.GetActionResponse(param, session, out needWrite); SocketGameResponse response = new SocketGameResponse(); HttpGet httpGet = new HttpGet(param, session.SessionId, session.Channel.RemoteEndPoint.ToString(), LoginSuccessCallback, session); OnRequested(httpGet, response); byte[] data = response.ReadByte(); ExSocket channel = session.Channel; var buffer = new byte[data.Length + 16]; Buffer.BlockCopy(ssid.ToByteArray(), 0, buffer, 0, 16); Buffer.BlockCopy(data, 0, buffer, 16, data.Length); try { socketLintener.PostSend(channel, buffer, 0, buffer.Length); } catch (Exception ex) { Logger.Error("PostSend异常", ex); } } catch (Exception ex) { Logger.Error("Task异常", ex); } finally { session.ExitSession(); Interlocked.Decrement(ref runningNum); } }
public bool SendDataBack(Guid ssid, byte[] data, int offset, int count) { try { ClientConnection clientConnection; if (!clientConnections.TryGetValue(ssid, out clientConnection)) { return(false); } ExSocket socket = clientConnection.Socket; listener.PostSend(socket, data, offset, count); return(true); } catch (Exception ex) { TraceLog.WriteError("SendDataBack error:{0}", ex); return(false); } }
private static GameSession OnCreate(Guid keyCode, params object[] args) { GameSession session; if (args.Length == 1) { session = new GameSession(keyCode, args[0]); } else if (args.Length == 2 && args[0] is ExSocket) { ExSocket socket = args[0] as ExSocket; var sendCallback = args[1] as Action <ExSocket, byte[], int, int>; session = new GameSession(keyCode, socket, sendCallback); } else { throw new ArgumentOutOfRangeException("param is error"); } _globalSession[keyCode] = session; return(session); }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { bool isOwner = ioEventArgs == null; if (socket.TryDequeueOrReset(out byte[] data)) { if (ioEventArgs == null) { ioEventArgsPool.TryPop(out ioEventArgs); ioEventArgs.AcceptSocket = socket.WorkSocket; bufferManager.SetBuffer(ioEventArgs); } var dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.ByteArrayForMessage = data; dataToken.MessageLength = data.Length; try { PostSend(ioEventArgs); } catch (Exception) { //dataToken.ResultCallback(ResultCode.Error, ex); if (isOwner) { ReleaseIOEventArgs(ioEventArgs); } //socket.ResetSendFlag(); } } else { ReleaseIOEventArgs(ioEventArgs); //socket.ResetSendFlag(); } }
// 真实服务器模式下 接收协议处理 private static void OnReceiveSocketPrtc(ExSocket exSocket, byte[] data) { if (data == null || data.Length < sizeof(int)) { HobaDebuger.LogWarning("Protocol Data Length is too short"); return; } int id = System.BitConverter.ToInt32(data, 0); byte[] pbs = null; if (data.Length > sizeof(int)) { int len = data.Length - sizeof(int); pbs = new byte[len]; System.Buffer.BlockCopy(data, 4, pbs, 0, len); } CS2CPrtcData prtc = _PrtcDataPool.GetObject(); prtc.Set(id, pbs); Instance().AddNewProtocol(prtc); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="handshakeData"></param> /// <returns></returns> protected override bool ResponseHandshake(ExSocket socket, HandshakeData handshakeData) { if (handshakeData.WebSocketVersion < _version) { return(base.ResponseHandshake(socket, handshakeData)); } string secKeyAccept = GenreateKey(handshakeData); StringBuilder response = new StringBuilder(); response.AppendLine(HandshakeHeadKeys.RespHead_10); response.AppendLine(HandshakeHeadKeys.RespUpgrade); response.AppendLine(HandshakeHeadKeys.RespConnection); response.AppendLine(string.Format(HandshakeHeadKeys.RespAccept, secKeyAccept)); if (!string.IsNullOrEmpty(handshakeData.Protocol)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespProtocol, handshakeData.Protocol)); } response.AppendLine(); Handler.SendMessage(socket, response.ToString(), Encoding); return(true); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="handshakeData"></param> /// <returns></returns> protected override bool ResponseHandshake(ExSocket socket, HandshakeData handshakeData) { string secKey1; string secKey2; byte[] secKey3; if (handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey1, out secKey1) && handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey2, out secKey2) && handshakeData.ParamItems.TryGet(HandshakeHeadKeys.SecKey3, out secKey3)) { //The minimum version support StringBuilder response = new StringBuilder(); response.AppendLine(HandshakeHeadKeys.RespHead_00); response.AppendLine(HandshakeHeadKeys.RespUpgrade00); response.AppendLine(HandshakeHeadKeys.RespConnection); string origin; if (handshakeData.ParamItems.TryGet(HandshakeHeadKeys.Origin, out origin)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespOriginLine, origin)); } response.AppendLine(string.Format(HandshakeHeadKeys.SecLocation, handshakeData.UriSchema, handshakeData.Host, handshakeData.UrlPath)); if (!string.IsNullOrEmpty(handshakeData.Protocol)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespProtocol, handshakeData.Protocol)); } response.AppendLine(); Handler.SendMessage(socket, response.ToString(), Encoding, result => { }); //Encrypt message byte[] securityKey = GetResponseSecurityKey(secKey1, secKey2, secKey3); Handler.SendMessage(socket, securityKey, result => { }); return true; } return false; }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="handshakeData"></param> /// <returns></returns> protected override bool ResponseHandshake(ExSocket socket, HandshakeData handshakeData) { if (handshakeData.WebSocketVersion < _version) { return base.ResponseHandshake(socket, handshakeData); } string secKeyAccept = GenreateKey(handshakeData); StringBuilder response = new StringBuilder(); response.AppendLine(HandshakeHeadKeys.RespHead_10); response.AppendLine(HandshakeHeadKeys.RespUpgrade); response.AppendLine(HandshakeHeadKeys.RespConnection); response.AppendLine(string.Format(HandshakeHeadKeys.RespAccept, secKeyAccept)); if (!string.IsNullOrEmpty(handshakeData.Protocol)) { response.AppendLine(string.Format(HandshakeHeadKeys.RespProtocol, handshakeData.Protocol)); } response.AppendLine(); Handler.SendMessage(socket, response.ToString(), Encoding, result => { }); return true; }
protected override void OnClosedStatus(ExSocket socket, int closeStatusCode) { Console.WriteLine("Receive client {0} close status code {1}.", socket.RemoteEndPoint, closeStatusCode); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public override byte[] CloseMessage(ExSocket exSocket, sbyte opCode, string reason) { byte[] data = Encoding.UTF8.GetBytes(reason); return BuildMessagePack(exSocket, opCode, data, 0, data.Length); }
private void InitSocket(ExSocket exSocket, ISocket appServer) { _exSocket = exSocket; _remoteAddress = _exSocket.RemoteEndPoint.ToNotNullString(); AppServer = appServer; }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { if (CheckVersion(exSocket)) { return(base.BuildMessagePack(exSocket, opCode, data, offset, count)); } bool isMask = IsMask; int maskNum = isMask ? MaskLength : 0; byte[] buffer; if (count < 126) { buffer = new byte[count + maskNum + 2]; //buffer[0] = 0x81; buffer[1] = (byte)count; //Buffer.BlockCopy(data, offset, buffer, 2, count); } else if (count < 0xFFFF) { //uint16 bit buffer = new byte[count + maskNum + 4]; //buffer[0] = 0x81; buffer[1] = 126; buffer[2] = (byte)(count / 256); buffer[3] = (byte)(count % 256); //Buffer.BlockCopy(data, offset, buffer, 4, count); } else { //uint64 bit buffer = new byte[count + maskNum + 10]; //buffer[0] = 0x81; buffer[1] = 127; int num2 = count; int num3 = 256; for (int i = 9; i > 1; i--) { buffer[i] = (byte)(num2 % num3); num2 /= num3; if (num2 == 0) { break; } } } if (isMask) { //mask after of payloadLength byte[] mask = GenerateMask(); int maskPos = buffer.Length - maskNum - count; Buffer.BlockCopy(mask, 0, buffer, maskPos, mask.Length); EncodeMask(data, offset, count, mask, buffer, buffer.Length - count); } else { Buffer.BlockCopy(data, offset, buffer, buffer.Length - count, count); } buffer[0] = (byte)((byte)opCode | 0x80); if (isMask) { buffer[1] = (byte)(buffer[1] | 0x80); } return(buffer); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public override byte[] CloseMessage(ExSocket exSocket, sbyte opCode, string reason) { return ClosingBytes; }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public override byte[] CloseMessage(ExSocket exSocket, sbyte opCode, string reason) { byte[] data = Encoding.UTF8.GetBytes(reason); return(BuildMessagePack(exSocket, opCode, data, 0, data.Length)); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="closeStatusCode"></param> protected virtual void OnClosedStatus(ExSocket socket, int closeStatusCode) { }
private void InitSocket(ExSocket exSocket, Action <ExSocket, byte[], int, int> sendCallback) { _exSocket = exSocket; _remoteAddress = _exSocket.RemoteEndPoint.ToString(); _sendCallback = sendCallback; }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <returns></returns> protected bool CheckVersion(ExSocket exSocket) { return(exSocket != null && exSocket.Handshake != null && exSocket.Handshake.WebSocketVersion < Version); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <returns></returns> protected bool CheckVersion(ExSocket exSocket) { return exSocket != null && exSocket.Handshake != null && exSocket.Handshake.WebSocketVersion < Version; }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="reason"></param> public override void CloseHandshake(ExSocket socket, string reason) { requestHandler.SendCloseHandshake(socket, OpCode.Close, reason); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { if (opCode == OpCode.Close) { return ClosingBytes; } byte[] buffer = new byte[count + 2]; buffer[0] = StartByte; Buffer.BlockCopy(data, offset, buffer, 1, count); buffer[count + 1] = EndByte; return buffer; }
/// <summary> /// Add session to cache /// </summary> /// <param name="keyCode"></param> /// <param name="socket"></param> /// <param name="sendCallback"></param> public static GameSession CreateNew(Guid keyCode, ExSocket socket, Action <ExSocket, byte[], int, int> sendCallback) { return(OnCreate(keyCode, socket, sendCallback)); }
/// <summary> /// Add session to cache /// </summary> /// <param name="keyCode"></param> /// <param name="socket"></param> /// <param name="appServer"></param> public static GameSession CreateNew(Guid keyCode, ExSocket socket, ISocket appServer) { return(OnCreate(keyCode, socket, appServer)); }
private GameSession(Guid sid, ExSocket exSocket, Action <ExSocket, byte[], int, int> sendCallback) : this(sid, null) { InitSocket(exSocket, sendCallback); }
private GameSession(Guid sid, ExSocket exSocket, ISocket appServer) : this(sid, null) { InitSocket(exSocket, appServer); }
private void InitSocket(ExSocket exSocket, Action <ExSocket, byte[], int, int> sendCallback) { _exSocket = exSocket; _sendCallback = sendCallback; }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="handshakeData"></param> protected abstract bool ResponseHandshake(ExSocket socket, HandshakeData handshakeData);
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { if (CheckVersion(exSocket)) { return base.BuildMessagePack(exSocket, opCode, data, offset, count); } bool isMask = IsMask; int maskNum = isMask ? MaskLength : 0; byte[] buffer; if (count < 126) { buffer = new byte[count + maskNum + 2]; //buffer[0] = 0x81; buffer[1] = (byte)count; //Buffer.BlockCopy(data, offset, buffer, 2, count); } else if (count < 0xFFFF) { //uint16 bit buffer = new byte[count + maskNum + 4]; //buffer[0] = 0x81; buffer[1] = 126; buffer[2] = (byte)(count / 256); buffer[3] = (byte)(count % 256); //Buffer.BlockCopy(data, offset, buffer, 4, count); } else { //uint64 bit buffer = new byte[count + maskNum + 10]; //buffer[0] = 0x81; buffer[1] = 127; int num2 = count; int num3 = 256; for (int i = 9; i > 1; i--) { buffer[i] = (byte)(num2 % num3); num2 /= num3; if (num2 == 0) { break; } } } if (isMask) { //mask after of payloadLength byte[] mask = GenerateMask(); int maskPos = buffer.Length - maskNum - count; Buffer.BlockCopy(mask, 0, buffer, maskPos, mask.Length); EncodeMask(data, offset, count, mask, buffer, buffer.Length - count); } else { Buffer.BlockCopy(data, offset, buffer, buffer.Length - count, count); } buffer[0] = (byte)((byte)opCode | 0x80); if (isMask) { buffer[1] = (byte)(buffer[1] | 0x80); } return buffer; }