一、Asp.Net Core6 后端,开启并绑定服务器端WebSocket
1. 启动文件启动绑定
//开启并绑定websocket
app.UseWebSockets();
app.Map("/wstest/one", con => {
con.UseWebSockets();
con.Use(async (ctx, next) => {
//创建监听websocket
WsTest ws = new WsTest();
await ws.DoWork(ctx);
await next.Invoke();
});
});
app.Run();
2.封装监听响应
public class WsTest
{
//当前请求实例
WebSocket socket = null;
public async Task DoWork(HttpContext ctx)
{
socket = await ctx.WebSockets.AcceptWebSocketAsync();
//执行监听
await EchoLoop();
}
public async Task EchoLoop()
{
//创建缓存区
var buffer = new byte[1024];
var seg = new ArraySegment<byte>(buffer);
while (this.socket.State == WebSocketState.Open)
{
var incoming = await this.socket.ReceiveAsync(seg, CancellationToken.None);
//判断类型读取
if (incoming.MessageType == WebSocketMessageType.Text)
{
//incoming.Count 代表,请求内容字节数量
string userMessage = Encoding.UTF8.GetString(seg.Array, 0, incoming.Count);
//接收客户的字符串
userMessage = "You sent: " + userMessage + " at " +
DateTime.Now.ToLongTimeString();
ArraySegment<byte> segResult = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
await socket.SendAsync(segResult, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
}
byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容结束");
var outgoing = new ArraySegment<byte>(backInfo, 0, backInfo.Length);
await this.socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
二、客户端连接并监听相应内容
1.html
<input id="Txt" type="text" name="name" value="" />
<button id="sendBtn">点击发送</button>
2.js
//创建监听测试
var url = 'ws://' + location.host + '/wstest/one';
var socket = new WebSocket(url);
//创建监听
socket.onopen = function (e) {
console.info('连接成功');
}
socket.onclose = function (e) {
console.info('连接关闭');
}
socket.onmessage = function (e) {
var data = e.data;
console.info(data);
}
socket.onerror = function (e) {
console.info(e);
}
//按钮事件中发送
document.getElementById('sendBtn').onclick = function () {
var text = document.getElementById('Txt').value;
console.info(text);
//执行发送
socket.send(text);
}
查看预览结果:
更多: