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(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; } } }