using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace Apewer.Source
{
///
public sealed class Redis : IDisposable
{
/// 最大长度。
public const int MaxLength = 1073741824;
private const int BufferSize = 1048576;
#region Instance
string _host = null;
string _pass = null;
int _port = 6379;
int _db = 0;
int _timeout = 1000; // 1000 毫秒。
Socket socket;
BufferedStream buffered;
/// 连接指定主机。
public Redis(string host, int port = 6379, string password = null)
{
_host = string.IsNullOrEmpty(host) ? "localhost" : host;
_port = (port < 1 || port > 65535) ? 6379 : port;
_pass = password;
_timeout = -1;
}
/// 连接 127.0.0.1 的指定端口。
public Redis(int port, string host = "127.0.0.1", string password = null) : this(host, port, password) { }
/// 连接 127.0.0.1 的 6379 端口。
public Redis() : this("127.0.0.1", 6379, null) { }
/// 获取或设置文本。
public string this[string key]
{
get { return GetText(key); }
set { SetText(key, value); }
}
/// 获取错误信息。
private Action Error { get; set; }
///
~Redis()
{
Dispose(false);
}
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
void Dispose(bool disposing)
{
if (disposing)
{
if (socket != null)
{
SendCommand("QUIT");
SendBySuccess();
socket.Close();
socket = null;
}
}
}
/// 连接 Redis 服务。
public string Connect()
{
try
{
if (socket != null && socket.Connected) return null;
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
socket.SendTimeout = _timeout;
socket.Connect(_host, _port);
if (!socket.Connected)
{
socket.Close();
socket = null;
return "Socket 连接失败。";
}
buffered = new BufferedStream(new NetworkStream(socket), BufferSize);
if (_pass != null) return SendBySuccess("AUTH", _pass);
return null;
}
catch (Exception ex)
{
var error = ex.GetType().Name + ": " + ex.Message;
return error;
}
}
#endregion
#region Static
// byte[] end_data = new byte[] { (byte)'\r', (byte)'\n' };
byte[] CRLF = new byte[] { 13, 10 };
static byte[] ToBytes(string text)
{
if (string.IsNullOrEmpty(text)) return new byte[0];
return Encoding.UTF8.GetBytes(text);
}
static int Length(string text)
{
return ToBytes(text).Length;
}
static string ToText(byte[] bytes)
{
if (bytes != null && bytes.Length > 0)
{
try
{
return Encoding.UTF8.GetString(bytes);
}
catch { }
}
return "";
}
#endregion
#region Common
T OnError(string message, T @return)
{
Error?.Invoke(message);
return @return;
}
object OnError(string message) => OnError