using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace web.Controllers { [Route("ws")] public class WebSocketController : Controller { public string Ip => this.Request.Headers["X-Real-IP"].FirstOrDefault() ?? this.Request.HttpContext.Connection.RemoteIpAddress.ToString(); /// /// 获取websocket分区 /// /// 本地标识,若无则不传,接口会返回新的,请保存本地localStoregy重复使用 /// [HttpPost("pre-connect")] async public Task preConnect([FromForm] Guid? websocketId) { if (websocketId == null) websocketId = Guid.NewGuid(); var server = WebChatHelper.GetServer(websocketId.Value); var token = $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}".Replace("-", ""); await RedisHelper.SetAsync($"webchat_token_{token}", Newtonsoft.Json.JsonConvert.SerializeObject((websocketId, this.Ip)), 10); return new { code = 0, server = $"ws://{server}/ws?token={token}", websocketId = websocketId }; } /// /// 群聊,获取群列表 /// /// [HttpPost("get-channels")] public object getChannels() { return new { code = 0, channels = WebChatHelper.GetChannels() }; } /// /// 群聊,绑定消息频道 /// /// 本地标识,若无则不传,接口会返回,请保存本地重复使用 /// 消息频道 /// [HttpPost("subscr-channel")] public object subscrChannel([FromForm] Guid? websocketId, [FromForm] string channel) { WebChatHelper.Subscribe(websocketId.Value, channel); return new { code = 0 }; } /// /// 群聊,发送频道消息,绑定频道的所有人将收到消息 /// /// 消息频道 /// 发送内容 /// [HttpPost("send-channelmsg")] public object sendChannelmsg([FromForm] string channel, [FromForm] string message) { WebChatHelper.Publish(channel, message); return new { code = 0 }; } /// /// 单聊 /// /// 发送者 /// 接收者 /// 发送内容 /// 是否需要回执 /// [HttpPost("send-msg")] public object sendmsg([FromForm] Guid senderWebsocketId, [FromForm] Guid receiveWebsocketId, [FromForm] string message, [FromForm] bool isReceipt = false) { WebChatHelper.SendMsg(senderWebsocketId, new[] { receiveWebsocketId }, message, isReceipt); return new { code = 0 }; } } }