欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.net webApi 通过WebSocket推送消息给客户端,搭建一个即是服务端又是客户端的服务

程序员文章站 2022-07-07 12:12:12
https://blog.csdn.net/IT_ziliang/article/details/96478794 WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通...

https://blog.csdn.net/IT_ziliang/article/details/96478794

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

废话不多说了,直接手把手教你如何通信

1、首先新建一个UserController继承自ApiController,然后写一个get方法供外部去调用。方法上一定加上 [HttpGet],代码如下
 

[HttpGet]
        public HttpResponseMessage GetConnect(string clientName)
        {
            HttpContext.Current.AcceptWebSocketRequest(ProcessRequest); //在服务器端接受Web Socket请求,传入的函数作为Web Socket的处理函数,待Web Socket建立后该函数会被调用,在该函数中可以对Web Socket进行消息收发
 
            return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //构造同意切换至Web Socket的Response.
        }
        ///记录客户端
        private static List<WebSocket> _sockets = new List<WebSocket>();
        ///接受信息和发送信息
        public async Task ProcessRequest(AspNetWebSocketContext context)
        {
            try
            {
                var socket = context.WebSocket;//传入的context中有当前的web socket对象
                _sockets.Add(socket);//此处将web socket对象加入一个静态列表中
 
                //进入一个无限循环,当web socket close是循环结束
                while (true)
                {
                    var buffer = new ArraySegment<byte>(new byte[1024]);
                    var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None);//对web socket进行异步接收数据
                    if (receivedResult.MessageType == WebSocketMessageType.Close)
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None);//如果client发起close请求,对client进行ack
                        _sockets.Remove(socket);
                        break;
                    }
 
                    if (socket.State == System.Net.WebSockets.WebSocketState.Open)
                    {
                        string recvMsg = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count);
                        var recvBytes = Encoding.UTF8.GetBytes(recvMsg);
                        var sendBuffer = new ArraySegment<byte>(recvBytes);
                        foreach (var innerSocket in _sockets)//当接收到文本消息时,对当前服务器上所有web socket连接进行广播
                        {
                            if (innerSocket != socket)
                            {
                                await innerSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);//lognet4日志记录
            }
        }
    }

 

2、如何做一个有信息就发送给所有客户端尼?就是再写个方法当作客户端发送信息给服务端就可以了,不用服务端去时时轮询。代码如下    这个方法就写在同一个类中,直接调用就行

        private readonly ClientWebSocket webSocket = new ClientWebSocket();
        private readonly CancellationToken _cancellation = new CancellationToken();
        ///客户端发送消息
        private async void SendMsg(object data)
        {
            try
            {
                await webSocket.ConnectAsync(new Uri("ws://localhost:8080/api/User?clientName=" + 123), _cancellation);
                var sendBytes = ObjectToBytes(data);//发送的数据
                var bsend = new ArraySegment<byte>(sendBytes);
                await webSocket.SendAsync(bsend, WebSocketMessageType.Binary, true, _cancellation);
                await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", _cancellation);
                webSocket.Dispose();//记得一定要释放不然服务端还产生很多连接
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);//lognet4日志记录
            }
        }

 

3、网页版的客户端代码如下

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
 <title></title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.3.min.js"></script>
 <script>
 var ws;
 $().ready(function () {
  $('#conn').click(function () {
  ws = new WebSocket('ws://localhost:8080' + '/api/user?clientName='+'456');
  $('#msg').append('<p>正在连接</p>');
 
  ws.onopen = function () {
   $('#msg').append('<p>已经连接</p>');
  }
  ws.onmessage = function (evt) {
   $('#msg').append('<p>' + evt.data + '</p>');
  }
  ws.onerror = function (evt) {
   $('#msg').append('<p>' + JSON.stringify(evt) + '</p>');
  }
  ws.onclose = function () {
   $('#msg').append('<p>已经关闭</p>');
  }
  });
 
  $('#close').click(function () {
  ws.close();
  });
 
  $('#send').click(function () {
  if (ws.readyState == WebSocket.OPEN) {
   ws.send($("#to").val() + "|" + $('#content').val());
  }
  else {
   $('#tips').text('连接已经关闭');
  }
  });
 
 });
 </script>
</head>
<body>
 <div>
 <input id="user" type="text" />
 <input id="conn" type="button" value="连接" />
 <input id="close" type="button" value="关闭"/><br />
 <span id="tips"></span>
 <input id="content" type="text" />
 <input id="send" type="button" value="发送"/><br />
 <input id="to" type="text" />目的用户
 <div id="msg">
 </div>
 </div>
</body>
</html>

 

4、C#控制台客户端的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace WebSocketClient
{
    class Program
    {
        static ClientWebSocket _webSocket = new ClientWebSocket();
        static CancellationToken _cancellation = new CancellationToken();
        static void Main(string[] args)
        {
            WebSocket();
            Console.Read();
        }
 
        public static async void WebSocket()
        {
            try
            {
 
                //建立连接
                var url = "ws://localhost:8080/api/User?clientName=" + 456;
 
                await _webSocket.ConnectAsync(new Uri(url), _cancellation);
                while (true)
                {
                    var result = new byte[1024];
                    await _webSocket.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
                    var str = Encoding.UTF8.GetString(result, 0, result.Length);
                    Console.WriteLine(str);//打印到控制台
                }
 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}