.Net Core 使用WebSocket

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;

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

QFN-齐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值