public class WebSocketXX
{
static private log4net.ILog log = log4net.LogManager.GetLogger(typeof(WebSocketXX )); //日志 没用就删了
WebSocket socket;
WebSocketXX(WebSocket socket)
{
this.socket = socket;
}
/// <summary>
/// 创建链接
/// </summary>
/// <param name="httpContext"></param>
/// <param name=""></param>
/// <returns></returns>
private static async Task Acceptor(Microsoft.AspNetCore.Http.HttpContext httpContext, Func<Task> n)
{
if (!httpContext.WebSockets.IsWebSocketRequest)
return;
var socket = await httpContext.WebSockets.AcceptWebSocketAsync();
var result = await RecvAsync(socket, CancellationToken.None);
}
/// <summary>
/// 接收客户端数据
/// </summary>
/// <param name="webSocket">webSocket 对象</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<string> RecvAsync(WebSocket webSocket, CancellationToken cancellationToken)
{
int isFirst = 0;
string oldRequestParam = "";
WebSocketReceiveResult result;
do
{
var ms = new MemoryStream();
var buffer = new ArraySegment<byte>(new byte[1024 * 8]);
result = await webSocket.ReceiveAsync(buffer, cancellationToken);
if (result.MessageType.ToString() == "Close")
{
break;
}
ms.Write(buffer.Array, buffer.Offset, result.Count - buffer.Offset);
ms.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(ms);
var s = reader.ReadToEnd();
reader.Dispose();
ms.Dispose();
if (!string.IsNullOrEmpty(s))
{
await SendAsync(s, webSocket);
}
oldRequestParam = s;
} while (result.EndOfMessage);
return "";
}
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="msg">数据</param>
/// <param name="webSocket">socket对象 sleep 心跳周期</param>
/// <returns></returns>
public static async Task SendAsync(string msg, WebSocket webSocket)
{
try
{
//业务逻辑
CancellationToken cancellation = default(CancellationToken);
var buf = Encoding.UTF8.GetBytes(结果信息。。。);
var segment = new ArraySegment<byte>(buf);
await webSocket.SendAsync(segment, WebSocketMessageType.Text, true, cancellation);
}
catch (Exception ex)
{
log.Error(ex);
}
}
/// 路由绑定处理
/// </summary>
/// <param name="app"></param>
public static void Map(IApplicationBuilder app)
{
app.UseWebSockets();
app.Use(WebSocketXX.Acceptor);
}
}
创建 WebSocketXX类
修改 Startup.cs 的Configure方法
app.Map("/WebSocketXX", Controllers.DataAnalysis.WebSocketXX.Map);
前端JS
var socket;
var uri = “ws://192.168.1.250:8090”+ "/WebSocketXX";
var output;
var text = { 'State': 0 };
$(function () {
//if (socket.readyState === 1) {
// doclose();
//}
load_init();
});
function load_init() {
socket = new WebSocket(uri);
setTimeout(function () {
console.log(socket.readyState);
socket.send(JSON.stringify(text));//发送
//doSend();
}, 1000);
//doSend();
}
//接受
function write(s) {
//console.log(s);
if (socket.readyState === 1) {
socket.send(JSON.stringify(text));
} else {
//do something
}
}
function doConnect() {
//alert(2);
socket.onopen = function (e) { write("opened " + uri); };
socket.onclose = function (e) { doConnect(); };
socket.onmessage = function (e) { write(e.data); };
socket.onerror = function (e) { console.log(e); write("Error: " + e.data); };
}
function doSend() {
//添加事件监听
socket.addEventListener('open', function () {
//write("Sending: " + text);
socket.send(JSON.stringify(text));
});
}
function onInit() {
output = document.getElementById("output");
doConnect();
}
function doclose() {
socket.onclose = function (e) {
console.log(e);
socket.close(); //关闭TCP连接
}
}
window.onload = onInit;