Asp.Net Core 使用WebSocket
2018-03-24 本文已影响576人
凌雲木
1.gif
2.gif
添加WebSocket中间件
app.UseWebSockets();
设置WebSocket连接
public async Task Connect(HttpContext context, Func<Task> n)
{
try
{
//执行接收
WebSocket socket = await context.WebSockets.AcceptWebSocketAsync();
this.socket = socket;
//执行监听
await WebSocketLoop();
}
catch (Exception ex)
{
throw ex;
}
}
设置WebSocket请求处理
async Task WebSocketLoop()
{
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);
var Receive = System.Text.UTF8Encoding.Default.GetString(seg.Array);
byte[] backInfo = System.Text.UTF8Encoding.Default.GetBytes($"格式有误,请检查{DateTime.Now}");
if (Receive.Contains("&"))
{
var ReceiveMessige= System.Text.UTF8Encoding.Default.GetString(seg.Array).Split('&');
//解析Json字符串为JObject
var result = JsonHelper.DeserializeJsonToObject<WebSocketBaseModel>(ReceiveMessige[0],out WebSocketBaseModel model);
if (result)
{
Thread.Sleep(model.SleepTime);
backInfo = System.Text.UTF8Encoding.Default.GetBytes("服务端相应内容:OK");
}
}
var ErrorOutgoing = new ArraySegment<byte>(backInfo, 0, backInfo.Length);
await this.socket.SendAsync(ErrorOutgoing, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
设置WebSocket客户端
<script>
var connectionForm = document.getElementById("connectionForm");
var connectionUrl = document.getElementById("connectionUrl");
var connectButton = document.getElementById("connectButton");
var stateLabel = document.getElementById("stateLabel");
var sendMessage = document.getElementById("sendMessage");
var sendButton = document.getElementById("sendButton");
var sendForm = document.getElementById("sendForm");
var commsLog = document.getElementById("commsLog");
var socket;
var scheme = document.location.protocol == "https:" ? "wss" : "ws";
var port = document.location.port ? (":" + document.location.port) : "";
connectionUrl.value = scheme + "://" + document.location.hostname + port + "@Url.Action("Connect")" ;
function updateState() {
function disable() {
sendMessage.disabled = true;
sendButton.disabled = true;
closeButton.disabled = true;
}
function enable() {
sendMessage.disabled = false;
sendButton.disabled = false;
closeButton.disabled = false;
}
connectionUrl.disabled = true;
connectButton.disabled = true;
if (!socket) {
disable();
} else {
switch (socket.readyState) {
case WebSocket.CLOSED:
stateLabel.innerHTML = "Closed";
disable();
connectionUrl.disabled = false;
connectButton.disabled = false;
break;
case WebSocket.CLOSING:
stateLabel.innerHTML = "Closing...";
disable();
break;
case WebSocket.CONNECTING:
stateLabel.innerHTML = "Connecting...";
disable();
break;
case WebSocket.OPEN:
stateLabel.innerHTML = "Open";
enable();
break;
default:
stateLabel.innerHTML = "Unknown WebSocket State: " + htmlEscape(socket.readyState);
disable();
break;
}
}
}
closeButton.onclick = function () {
if (!socket || socket.readyState != WebSocket.OPEN) {
alert("socket not connected");
}
socket.close(1000, "Closing from client");
}
sendButton.onclick = function () {
if (!socket || socket.readyState != WebSocket.OPEN) {
alert("socket not connected");
}
var data = sendMessage.value;
socket.send(data);
commsLog.innerHTML += '<tr>' +
'<td class="commslog-client">Client</td>' +
'<td commslog-data">========></td>' +
'<td class="commslog-server">Server</td>' +
'<td class="commslog-data">' + htmlEscape(data) + '</td>'
'</tr>';
}
connectButton.onclick = function() {
stateLabel.innerHTML = "Connecting";
socket = new WebSocket(connectionUrl.value);
socket.onopen = function (event) {
updateState();
commsLog.innerHTML += '<tr>' +
'<td colspan="4" class="commslog-data">Connection opened</td>' +
'</tr>';
};
socket.onclose = function (event) {
updateState();
commsLog.innerHTML += '<tr>' +
'<td colspan="4" class="commslog-data">Connection closed. Code: ' + htmlEscape(event.code) + '. Reason: ' + htmlEscape(event.reason) + '</td>' +
'</tr>';
};
socket.onerror = updateState;
socket.onmessage = function (event) {
console.log(event.data);
commsLog.innerHTML += '<tr>' +
'<td class="commslog-server">Server</td>' +
'<td commslog-data">========></td>' +
'<td class="commslog-client">Client</td>' +
'<td class="commslog-data">' + htmlEscape(event.data) + '</td>'
'</tr>';
};
};
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
</script>