基于WebAPI的websocket示例

客户端JS代码:

<!DOCTYPE html>
<html>
<head>
    <title>websocket client</title>
    <script type="text/javascript">
        //**************zzt****************
        var webSocket;
        //HTTP处理程序的地址
        var handlerUrl = "ws://localhost:8082/api/Values";

        function doConnection() {
            InitWebSocket();
        }

        function SendData() {
            var input = document.getElementById('sendText');
            //初始化WebSocket
            InitWebSocket();
            //如果WebSocket打开,发送数据
            if (webSocket.OPEN && webSocket.readyState == 1) {
                if (input.value != "")
                    webSocket.send(input.value);
            }

            //如果WebSocket关闭,显示消息
            if (webSocket.readyState == 2 || webSocket.readyState == 3) {
                alert("WebSocket关闭了,无法发送数据");
            }
        }

        function CloseWebSocket() {
            webSocket.close();
            webSocket = undefined;
        }

        function InitWebSocket() {

            //如果WebSocket对象未初始化,我们将初始化它
            if (webSocket == undefined) {
                webSocket = new WebSocket(handlerUrl);

                //打开连接处理程序
                webSocket.onopen = function () {
                    alert("WebSocket已连接");
                };

                //消息数据处理程序
                webSocket.onmessage = function (e) {
                    alert(e.data);
                };

                //关闭事件处理程序
                webSocket.onclose = function () {
                    alert("WebSocket closed.");
                };

                //错误事件处理程序
                webSocket.onerror = function (e) {
                    alert(e.message);
                };
            }
            else {
                //webSocket.open();没有open方法
            }
        }

        function doDeleteConnection(devid) {
            //初始化WebSocket
            InitWebSocket();

            //如果WebSocket打开,发送数据
            if (webSocket.OPEN && webSocket.readyState == 1) {

                webSocket.send("DelConnection^" + devid);
            }

            //如果WebSocket关闭,显示消息
            if (webSocket.readyState == 2 || webSocket.readyState == 3) {
                //document.getElementById("di_span").innerText = "WebSocket关闭了,无法发送数据";
                alert("WebSocket关闭了,无法发送数据");
            }
        }
            //**************zztend*************

    </script>
</head>
<body>
    <form id="sendForm">
        <input id="sendText" placeholder="Text to send" />
        <button type="button" onclick="doConnection();">连接</button>
        <button type="button" onclick="SendData();">发送</button>
        <button type="button" onclick="CloseWebSocket();">关闭</button>
    </form>
</body>
</html>

服务端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.WebSockets;

namespace WebSocketServer.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public HttpResponseMessage Get()
        {
            //检查 查询是否是WebSocket请求
            if (HttpContext.Current.IsWebSocketRequest)
            {
                //如果是,我们附加异步处理程序
                HttpContext.Current.AcceptWebSocketRequest(ProcessWSMsg);
            }
            return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
            检查 查询是否是WebSocket请求
            //if (HttpContext.Current.IsWebSocketRequest)
            //{
            //    //如果是,我们附加异步处理程序
            //    HttpContext.Current.AcceptWebSocketRequest(ProcessWSMsg);
            //}
        }

        private async Task ProcessWSMsg(AspNetWebSocketContext arg)
        {
            //获取当前的WebSocket对象
            WebSocket webSocket = arg.WebSocket;

            /*
             * 我们定义一个常数,它将表示接收到的数据的大小。 它是由我们建立的,我们可以设定任何值。 我们知道在这种情况下,发送的数据的大小非常小。
            */
            const int maxMessageSize = 1024;

            //received bits的缓冲区
            var receivedDataBuffer = new ArraySegment<Byte>(new Byte[maxMessageSize]);

            var cancellationToken = new CancellationToken();

            //检查WebSocket状态
            while (webSocket.State == WebSocketState.Open)
            {
                //读取数据 
                WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken);

                //如果输入帧为取消帧,发送close命令
                if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationToken);
                }
                else
                {
                    byte[] payloadData = receivedDataBuffer.Array.Where(b => b != 0).ToArray();

                    //因为我们知道这是一个字符串,我们转换它
                    string receiveString = System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length);

                    //将字符串转换为字节数组. 
                    var newString = String.Format("Hello, " + receiveString + " ! Time {0}", DateTime.Now.ToString());
                    Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(newString);

                    //发回数据
                    await webSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, cancellationToken);
                }

            }
        }

    }
}

服务端代码发布到IIS上。客户端JS运行结果:

服务端返回给客户端的消息( webSocket.onmessage事件监听):

posted @ 2018-12-20 21:00  漂移青春  阅读(542)  评论(0编辑  收藏  举报