1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using VueWebApi.Tools;
 
namespace VueWebApi.Controllers
{
    [RoutePrefix(prefix: "api/Send")]
    [ControllerGroup("消息提醒", "在线接口")]
    public class SendController : ApiController
    {
        private readonly ClientWebSocket webSocket = new ClientWebSocket();
        private readonly CancellationToken _cancellation = new CancellationToken();
 
        [HttpGet]
        public async Task SendMsg(string msg)
        {
            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();
        }
 
        //http://localhost:port/api/Send/Init
        [HttpGet]
        public string Init()
        {
            TestSocket.Instance.socketServer();
            return "success";
        }
 
        [HttpGet]
        public string Msg(string userid, string msg)
        {
            var _msg = TestSocket.Instance.Send(userid, msg);
            return _msg;
        }
    }
}