public bool TryParseResponse(RedisSocket socket, string textHeader, out byte[][] result) { int size; if (!int.TryParse(textHeader, out size)) { throw new Exception("Invalid length"); } if (size == -1) { result = new byte[0][]; return(true); } result = new byte[size][]; for (int index = 0; index < size; index++) { var bHeader = socket.ReadByte(); var sHeader = socket.ReadLine(); if (!BulkByteParser.CheckExpetedHeader(bHeader)) { throw new Exception("Invalid byte array content"); } if (!BulkByteParser.TryParseResponse(socket, sHeader, out result[index])) { throw new Exception("Invalid byte array content"); } } return(true); }
//默认回调函数 public void default_On_cmd_set_callback(RedisSocket redis_socket, string[] cmd_set) { for (int i = 0; i < cmd_set.Length; i++) { Debug.Log(string.Format("default_On_cmd_set_callback:{0}/{1} {2}[{3}]", i, cmd_set.Length, cmd_set[i].Length, cmd_set[i])); } }
static ExecCmdListenResult ExecCmdListen(Action <ExecCmdListenResult, string> ondata, string cmd, string subcmd = null, params object[] parms) { var args = PrepareCmd(cmd, subcmd, parms); var rds = RedisSocket.GetRedisSocket(); Resp3Helper.Write(rds.Stream, args, true); var rd = Resp3Helper.Read <string>(rds.Stream); var rt = new ExecCmdListenResult { rds = rds }; new Thread(() => { ondata?.Invoke(rt, rd.Value); while (rt._running) { try { ondata?.Invoke(rt, Resp3Helper.Read <string>(rds.Stream).Value); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }).Start(); return(rt); }
public bool TryParseResponse(RedisSocket socket, string textHeader, out byte[] result) { int size; if (!int.TryParse(textHeader, out size)) { result = null; return(false); } if (size < 0) { result = null; return(true); } result = new byte[size]; socket.Read(result, 0, size); if (socket.ReadByte() != '\r' || socket.ReadByte() != '\n') { throw new Exception("Invalid termination"); } return(true); }
private static ulong ReadNextPointer(RedisSocket socket) { var bHeader = socket.ReadByte(); var sHeader = socket.ReadLine(); if (!BulkByteParser.CheckExpetedHeader(bHeader)) { throw new Exception("Invalid pointer content"); } byte[] buffer; if (!BulkByteParser.TryParseResponse(socket, sHeader, out buffer)) { throw new Exception("Invalid pointer content"); } var number = buffer.ToUtf8String(); ulong result; if (ulong.TryParse(number, out result)) { } return(result); }
public void On_cmd_set_callback1(RedisSocket redis_socket, string[] cmd_set) { StringBuilder sb = new StringBuilder(); JsonWriter jw = new JsonWriter(sb); jw.Write(cmd_set); Debug.Log("On_cmd_set_callback1 cmd_set=" + sb.ToString()); }
protected virtual void Dispose(bool disposing) { if (disposing) { this.OnDisconnecting(); this.socket.Dispose(); this.socket = null; } }
private static void SendBuffer(RedisSocket socket, PooledByteBuffer buffer) { buffer.StartRead(); var bytes = new byte[ReadBufferSize]; var bytesRead = 0; while ((bytesRead = buffer.Read(bytes, 0, bytes.Length)) > 0) { socket.Write(bytes, 0, bytesRead); } }
static Resp3Helper.ReadResult <T> ExecCmd <T>(string cmd, string subcmd = null, params object[] parms) { var args = PrepareCmd(cmd, subcmd, parms); using (var rds = RedisSocket.GetRedisSocket()) { Resp3Helper.Write(rds.Stream, args, true); var rt = Resp3Helper.Read <T>(rds.Stream); return(rt); } }
public void On_cmd_set_callback2(RedisSocket redis_socket, string[] cmd_set) { StringBuilder sb = new StringBuilder(); JsonWriter jw = new JsonWriter(sb); jw.Write(cmd_set); Debug.Log("On_cmd_set_callback2 cmd_set=" + sb.ToString()); for (int i = 0; i < cmd_set.Length; i++) { Debug.Log(string.Format("mp.On_cmd_set_callback2:{0}/{1} {2}[{3}]", i, cmd_set.Length, cmd_set[i].Length, cmd_set[i])); } }
public static void ReadCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; RedisSocket redis_socket = state.redis_socket; Socket sock = state.socket; int bytesRead = sock.EndReceive(ar); if (bytesRead > 0) { redis_socket.on_data(state.buffer, bytesRead); sock.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } }
private void CheckSocketStatus() { if (this.Connected) { return; } if (this.socket != null) { this.socket.Dispose(); this.socket = null; } this.socket = new RedisSocket(this.Host, this.Port, this.UseSsl, this.ConnectionTimeout, this.ConnectionTimeout); this.OnConnecting(); }
public bool Send(RedisSocket redisSocket, byte[][] commands) { try { using (var buffer = BufferPool.GetObject()) { WriteInBuffer(buffer, commands); SendBuffer(redisSocket, buffer); } } catch (Exception) { return(false); } return(true); }
private static byte[][] ReadArrayResult(RedisSocket socket) { var bHeader = socket.ReadByte(); var sHeader = socket.ReadLine(); if (!BulkByteArrayParser.CheckExpetedHeader(bHeader)) { throw new Exception("Invalid data content"); } byte[][] result; if (!BulkByteArrayParser.TryParseResponse(socket, sHeader, out result)) { throw new Exception("Invalid data content"); } return(result); }
public T Receive(RedisSocket socket) { var byteHeader = socket.ReadByte(); var textHeader = socket.ReadLine(); CheckFailState(byteHeader, textHeader); if (!parser.CheckExpetedHeader(byteHeader)) { ThrowUnknownReplyException(byteHeader, textHeader); } T result; if (!parser.TryParseResponse(socket, textHeader, out result)) { ThrowUnknownReplyException(byteHeader, textHeader); } return(result); }
public bool TryParseResponse(RedisSocket socket, string textHeader, out RedisScanResult result) { int size; if (!int.TryParse(textHeader, out size)) { throw new Exception("Invalid length"); } if (size != 2) { throw new Exception("Invalid scan result content"); } var nextPointer = ReadNextPointer(socket); var arrayResult = ReadArrayResult(socket); result = new RedisScanResult(nextPointer, arrayResult); return(true); }
public RedisRawResponse Execute(RedisSocket socket) { if (base.BeginReading()) { try { var result = base.ReadResponse(socket); if (ReferenceEquals(result, null) && result.IsVoid) { return(null); } return(result); } finally { EndReading(); } } return(null); }
/* * public static string redis_cmd(string[] cmd_set) * { * System.Text.UTF8Encoding c=new System.Text.UTF8Encoding(); * * string data = string.Format ("*{0}\r\n", cmd_set.Length); * for(int i=0;i<cmd_set.Length;i++) * { * byte[] d = c.GetBytes (cmd_set [i]);// System.Convert.FromBase64String(cmd_set[i]); * data += string.Format ("${0}\r\n{1}\r\n", d.Length, cmd_set [i]); * } * data += "\r\n"; * return data; * }*/ //测试 public static void test() { JsonReader jr = new JsonReader(tools.file_get_contents("config.json")); Dictionary <string, object> config = (Dictionary <string, object>)jr.Deserialize(); ChanelMp mp1 = Instance(); mp1.set_method("C2S_玩家登陆"); mp1.set_param("gid", "1_3"); tools.file_put_contents("hello.txt", tools.to_json(mp1, true)); RedisSocket c1 = new RedisSocket(); RedisSocket c2 = new RedisSocket(); c1.cfg((string)config["c1_host"], (int)config["c1_port"]); c2.cfg((string)config["c2_host"], (int)config["c2_port"]); string cmdline = "hello word 消息信息!"; c2.on_data(cmdline); c2.On_cmd_set_callback = new On_cmd_set_callback(mp1.On_cmd_set_callback2); c1.On_cmd_set_callback = new On_cmd_set_callback(mp1.On_cmd_set_callback1); c1.send(new string[] { "set", "a", "a===1" }); c1.send(new string[] { "set", "b", "b===2" }); c1.send(new string[] { "set", "c", "c===3" }); c1.send(new string[] { "keys", "*" }); c1.send(new string[] { "get", "c" }); //c1.send(new string[] { "subscribe", "h", "g", "b" }); c1.send("psubscribe h g b"); //file_put_contents ("hello.txt", redis_cmd (cmd_set)); Debug.Log("--------"); // c2.game_call (mp1); }
public bool TryParseResponse(RedisSocket socket, string textHeader, out double result) { return(double.TryParse(textHeader, NumberStyles.Any, (IFormatProvider)CultureInfo.InvariantCulture.NumberFormat, out result)); }
public IOperation <double> CreateDoubleOperation(RedisSocket socket) { return(new Operation <double>(socket, new OperationRequest(), new OperationResponse <double>(DoubleParser))); }
public IOperation <long> CreateInt64Operation(RedisSocket socket) { return(new Operation <long>(socket, new OperationRequest(), new OperationResponse <long>(Int64Parser))); }
public IOperation <byte[][]> CreateMultiDataOperation(RedisSocket socket) { return(new Operation <byte[][]>(socket, new OperationRequest(), new OperationResponse <byte[][]>(BulkByteArrayParser))); }
public IOperation <string> CreateStringOperation(RedisSocket socket) { return(new Operation <string>(socket, new OperationRequest(), new OperationResponse <string>(SimpleStringParser))); }
public IOperation <RedisScanResult> CreateScanOperation(RedisSocket socket) { return(new Operation <RedisScanResult>(socket, new OperationRequest(), new OperationResponse <RedisScanResult>(ScanResultParser))); }
public Operation(RedisSocket socket, IOperationRequest request, IOperationResponse <T> response) { this.socket = socket; this.request = request; this.response = response; }
private async Task ConnectAsync(CancellationToken cancellationToken) { if (IsConnected) { return; } LastAction = "Waiting for Connecting lock to be free"; var wait = _connectSemaphoreSlim.WaitAsync(cancellationToken); if (!wait.IsCompletedSuccessfully()) { await wait.ConfigureAwait(false); } try { if (IsConnected) { return; } LastAction = "Connecting"; Interlocked.Increment(ref _reconnectAttempts); _socket = new RedisSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = ClientConfig.SendTimeoutMillis, ReceiveTimeout = ClientConfig.ReceiveTimeoutMillis }; OptimiseSocket(); if (IPAddress.TryParse(ClientConfig.Host, out var ip)) { await _socket.ConnectAsync(ip, ClientConfig.Port).ConfigureAwait(false); } else { var addresses = await Dns.GetHostAddressesAsync(ClientConfig.Host); await _socket.ConnectAsync( addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork), ClientConfig.Port).ConfigureAwait(false); } if (!_socket.Connected) { Log.Debug("Socket Connect failed"); _socket.Close(); _socket = null; return; } Log.Debug("Socket Connected"); Stream networkStream = new NetworkStream(_socket); var redisPipeOptions = GetPipeOptions(); if (ClientConfig.Ssl) { _sslStream = new SslStream(networkStream, false, ClientConfig.CertificateValidationCallback, ClientConfig.CertificateSelectionCallback, EncryptionPolicy.RequireEncryption); LastAction = "Authenticating SSL Stream as Client"; await _sslStream.AuthenticateAsClientAsync(ClientConfig.Host).ConfigureAwait(false); if (!_sslStream.IsEncrypted) { Dispose(); throw new SecurityException($"Could not establish an encrypted connection to Redis - {ClientConfig.Host}"); } LastAction = "Creating SSL Stream Pipe"; _pipe = StreamPipe.GetDuplexPipe(_sslStream, redisPipeOptions.SendOptions, redisPipeOptions.ReceiveOptions); } else { LastAction = "Creating Socket Pipe"; _pipe = SocketPipe.GetDuplexPipe(_socket, redisPipeOptions.SendOptions, redisPipeOptions.ReceiveOptions); } IsConnected = true; if (!string.IsNullOrEmpty(ClientConfig.Password)) { LastAction = "Authorizing"; await Authorize(cancellationToken); } if (ClientConfig.Db != 0) { LastAction = "Selecting Database"; await SelectDb(cancellationToken); } if (ClientConfig.ClientName != null) { LastAction = "Setting Client Name"; await SetClientNameAsync(cancellationToken); } } finally { _connectSemaphoreSlim.Release(); } }
public bool TryParseResponse(RedisSocket socket, string textHeader, out long result) { return(long.TryParse(textHeader, out result)); }
public StateObject(RedisSocket _redis_socket, Socket _socket) { redis_socket = _redis_socket; socket = _socket; }
//发送函数 public static void On_redis_cmd_set_callback1(RedisSocket redis_server, string[] cmd_set) { string msg = tools.to_json(cmd_set); Debug.Log("On_redis_cmd_set_callback1:" + msg); }
//接收函数 public static void On_redis_cmd_set_callback2(RedisSocket redis_server, string[] cmd_set) { cmd_set_list.Add(cmd_set); }