public static string getAuthUrl(string hostUrl, string apiKey, string apiSecret)
{
Uri uri = new Uri(hostUrl);
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string date = DateTime.UtcNow.ToUniversalTime().ToString(CultureInfo.CurrentCulture.DateTimeFormat.RFC1123Pattern, new System.Globalization.CultureInfo("en-us"));
StringBuilder builder = new StringBuilder("host: ").Append(uri.Host).Append("\n").//
Append("date: ").Append(date).Append("\n").//
Append("GET ").Append(uri.LocalPath).Append(" HTTP/1.1");
byte[] hexDigits;
string sha;
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(apiSecret)))
{
hexDigits = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString()));
sha = Convert.ToBase64String(hexDigits);
}
string authorization = string.Format("hmac username=\"{0}\", algorithm=\"{1}\", headers=\"{2}\", signature=\"{3}\"", apiKey, "hmac-sha256", "host date request-line", sha);
Debug.Log(authorization);
hostUrl += "?authorization=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(authorization)) + "&date=" + date + "&host=" + uri.Host;
return hostUrl;
}
public async void WebSocket()
{
try
{
//ClientWebSocket ws = new ClientWebSocket();
//CancellationToken ct = new CancellationToken();
string authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
Debug.Log(authUrl);
Uri url = new Uri(authUrl);
await ws.ConnectAsync(url, ct);
//await ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("hello")), WebSocketMessageType.Binary, true, ct); //发送数据
isSocket = true;
while (true)
{
var result = new byte[1024];
await ws.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
var str = Encoding.UTF8.GetString(result, 0, result.Length);
onMessage(str);
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}