| | |
| | | using System; |
| | | using System.Collections.Generic; |
| | | using System.Linq; |
| | | using System.IO; |
| | | using System.Net; |
| | | using System.Net.Http; |
| | | using System.Net.WebSockets; |
| | | using System.Runtime.Serialization; |
| | | using System.Runtime.Serialization.Formatters.Binary; |
| | | using System.Text; |
| | | using System.Threading; |
| | | using System.Threading.Tasks; |
| | | using System.Web; |
| | | using System.Web.Http; |
| | | using System.Web.WebSockets; |
| | | using VueWebApi.Tools; |
| | | |
| | | namespace VueWebApi.Controllers |
| | | { |
| | | [RoutePrefix(prefix: "api/Send")] |
| | | [RoutePrefix(prefix: "Send")] |
| | | [ControllerGroup("消息提醒", "在线接口")] |
| | | public class SendController : ApiController |
| | | { |
| | | private readonly ClientWebSocket webSocket = new ClientWebSocket(); |
| | | private readonly CancellationToken _cancellation = new CancellationToken(); |
| | | |
| | | /// <summary> |
| | | /// 登录用户建立WebSocket服务连接 |
| | | /// </summary> |
| | | /// <param name="clientName">登录用户信息</param> |
| | | /// <returns></returns> |
| | | [HttpGet] |
| | | public async Task SendMsg(string msg) |
| | | public HttpResponseMessage GetConnect(string clientName) |
| | | { |
| | | await webSocket.ConnectAsync(new Uri("ws://localhost:8001"), _cancellation); |
| | | var sendBytes = Encoding.UTF8.GetBytes(msg);//发送的数据 |
| | | var bsend = new ArraySegment<byte>(sendBytes); |
| | | await webSocket.SendAsync(bsend, WebSocketMessageType.Binary, true, _cancellation); |
| | | await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "1", _cancellation); |
| | | webSocket.Dispose(); |
| | | 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) |
| | | { |
| | | throw new Exception(ex.Message); |
| | | } |
| | | } |
| | | |
| | | //http://localhost:port/api/Send/Init |
| | | [HttpGet] |
| | | public string Init() |
| | | { |
| | | TestSocket.Instance.socketServer(); |
| | | return "success"; |
| | | } |
| | | |
| | | [HttpGet] |
| | | public string Msg(string userid, string msg) |
| | | //客户端发送消息 |
| | | private async void SendMsg(object data) |
| | | { |
| | | var _msg = TestSocket.Instance.Send(userid, msg); |
| | | return _msg; |
| | | try |
| | | { |
| | | await webSocket.ConnectAsync(new Uri("wss://121.196.36.24:8001/api/Send?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) |
| | | { |
| | | throw new Exception(ex.Message); |
| | | } |
| | | } |
| | | public static byte[] ObjectToBytes(object obj) |
| | | { |
| | | using (MemoryStream ms = new MemoryStream()) |
| | | { |
| | | IFormatter formatter = new BinaryFormatter(); |
| | | formatter.Serialize(ms, obj); |
| | | return ms.GetBuffer(); |
| | | } |
| | | } |
| | | } |
| | | } |