.net websocket返回参数使用gzip压缩,微信小程序使用pako解压
程序员文章站
2024-03-13 23:43:28
...
.Net 使用MVC,并且用自带的WebSocket组件
微信小程序需要下载应并引用pako.min.js,下载地址:https://github.com/nodeca/pako
- 控制器:
/// <summary>
/// websocket请求
/// </summary>
public class DoCenterListController : ApiController
{
/// <summary>
/// 日志对象
/// </summary>
private static Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// websocket请求
/// </summary>
/// <returns></returns>
[HttpGet]
public HttpResponseMessage DoCenterListWebSocket()
{
if (HttpContext.Current.IsWebSocketRequest)
{
HttpContext.Current.AcceptWebSocketRequest(GetList);
}
return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
}
/// <summary>
/// 获取列表
/// </summary>
/// <param name="context">HttpContext</param>
/// <returns></returns>
private async Task GetList(AspNetWebSocketContext context)
{
WebSocket socket = context.WebSocket;
try
{
while (true)
{
if (socket.State == WebSocketState.Open)
{
#region 接收请求
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult receiveResult = await socket.ReceiveAsync(buffer, CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
logger.Warn(GetLogMsg(context) + ",客户端请求关闭。");
break;
}
string parameter = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
DoCenterParameterModel model = JsonConvert.DeserializeObject<DoCenterParameterModel>(parameter);
logger.Info(GetLogMsg(context) + ",参数:" + parameter + ",请求开始。");
#endregion
#region 返回参数
//code业务代码
string parameter = "返回内容";
byte[] result = GzipHelper.GzipCompressBytes(parameter);
ArraySegment<byte> returnBuffer = new ArraySegment<byte>(result);
await socket.SendAsync(returnBuffer, WebSocketMessageType.Binary, true, CancellationToken.None);
#endregion
}
else
{
logger.Warn(GetLogMsg(context) + ",连接关闭。");
break;
}
}
}
catch (Exception ex)
{
await socket.CloseOutputAsync(WebSocketCloseStatus.InternalServerError, ex.Message, CancellationToken.None);
logger.Error(ex.Message);
}
}
/// <summary>
/// 获取日志内容前缀
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private string GetLogMsg(AspNetWebSocketContext context)
{
return "请求路径:" + context.RequestUri.AbsoluteUri;
}
}
- gzip帮助类
/// <summary>
/// GZIP压缩和解压
/// </summary>
public class GzipHelper
{
/// <summary>
/// GZIP压缩(返回string)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GzipCompressStr(string str)
{
if(!string.IsNullOrEmpty(str))
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
byte[] result = GzipCompress(buffer);
return Convert.ToBase64String(result);
}
else
{
return str;
}
}
/// <summary>
/// GZIP压缩(返回bytes)
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static byte[] GzipCompressBytes(string str)
{
if (!string.IsNullOrEmpty(str))
{
byte[] buffer = Encoding.UTF8.GetBytes(str);
return GzipCompress(buffer);
}
else
{
return null;
}
}
/// <summary>
/// GZIP压缩
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static byte[] GzipCompress(byte[] buffer)
{
MemoryStream ms = new MemoryStream();
GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true);
gzip.Write(buffer, 0, buffer.Length);
gzip.Close();
ms.Close();
return ms.ToArray();
//切记不能使用以下代码
//using (MemoryStream ms = new MemoryStream())
//{
// using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress,true))
// {
// gzip.Write(buffer, 0, buffer.Length);
// return ms.ToArray();
// }
//}
}
/// <summary>
/// GZIP解压
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GzipDecompress(string str)
{
if (!string.IsNullOrEmpty(str))
{
byte[] buffer = Convert.FromBase64String(str);
byte[] result = GzipDecompress(buffer);
return Encoding.UTF8.GetString(result);
}
else
{
return str;
}
}
/// <summary>
/// GZIP解压
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static byte[] GzipDecompress(byte[] buffer)
{
using (MemoryStream ms = new MemoryStream(buffer))
{
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress))
{
using (MemoryStream outBuffer = new MemoryStream())
{
try
{
byte[] block = new byte[1024];
while (true)
{
int bytesRead = gzip.Read(block, 0, block.Length);
if (bytesRead <= 0)
{
break;
}
else
{
outBuffer.Write(block, 0, bytesRead);
}
}
}
catch (Exception ex)
{
}
return outBuffer.ToArray();
}
}
}
}
}
- 微信小程序
var pako = require('../../../utils/pako.min.js');
onLoad: function() {
var ws1 = wx.connectSocket({//打开websocket连接
url: 'wss://test.com/ws1',
success: function (resConnect) {//打开连接成功
// console.log(resConnect)
},
fail: function (resConnectError) {//打开连接失败
// console.log(resConnectError)
}
})
ws1.onOpen(function(res){
if (ws1.readyState === 1){
ws1.send({
data: JSON.stringify({
number: '123',
}),
success: function (resSend) {
// console.log(resSend)
},
fail: function (resSendError) {
// console.log(resSendError)
}
})
}
})
ws1.onMessage(function (data) {
var restored = pako.ungzip(data.data, { to: 'string' });
console.log(restored)
})
},