小程序WebSocket 简单实例
程序员文章站
2022-04-09 16:45:03
...
<button bindtap='startConnect'>创建连接</button>
<button bindtap='sendOne'>发送内容</button>
<button bindtap='closeOne'>关闭连接</button>
//创建连接
startConnect: function () {
//本地测试使用 ws协议 ,正式上线使用 wss 协议
var url = 'ws://localhost:61870/socketone/one?user=lisi';
wxst = wx.connectSocket({
url: url,
method: "GET"
});
wxst.onOpen(res => {
console.info('连接打开成功');
});
wxst.onError(res => {
console.info('连接识别');
console.error(res);
});
wxst.onMessage(res => {
var data = res.data;
console.info(data);
});
wxst.onClose(() => {
console.info('连接关闭');
});
},
//发送内容
sendOne: function () {
if (wxst.readyState == wxst.OPEN) {
wxst.send({
data: '小程序端测试',
success: () => {
console.info('客户端发送成功');
}
});
} else {
console.error('连接已经关闭');
}
},
//关闭连接
closeOne: function () {
wxst.close();
},
二、后台Asp.Net MVC启用WebSocket
注:当前示例仅考虑了单个链接的打开,对于多页面打开或者换浏览器打开的情况没做处理。
/// <summary>
/// Socket后台代码示例
/// </summary>
public class SocketOneController : Controller
{
static Dictionary<string, WebSocket> CONNECT_POOL = new Dictionary<string, WebSocket>();//用户连接池
//测试1,定义socke监听
public void One(string user)
{
HttpContextBase context = ControllerContext.HttpContext;
context.AcceptWebSocketRequest(async (ctx) =>
{
//开启socket监听
WebSocket socket = ctx.WebSocket;
while (true)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
CancellationToken token;
if (socket.State == WebSocketState.Open)
{
//后台上线处理
if (CONNECT_POOL.Keys.Contains(user) == false)
CONNECT_POOL.Add(user, socket);
WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, token);
string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
userMessage = "You sent: " + userMessage + " at " +
DateTime.Now.ToLongTimeString();
//响应处理
buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
//离线处理
CONNECT_POOL.Remove(user);
break;
}
}
});
}
//后台执行发送操作
public string Handle(string user)
{
if (CONNECT_POOL.Keys.Contains(user) == false)
return "当前连接已经断开";
WebSocket socket = CONNECT_POOL[user];
byte[] bytes = Encoding.UTF8.GetBytes($"后台发送通知 at {DateTime.Now.ToString()}");
ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);
socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
return "操作成功";
}
}
下一篇: 亚洲简介 亚洲一共有多少个国家?