using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
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;
using System.Web.Http;
using System.Web.WebSockets;
namespace WebApiDemo.Controllers
{
public class SocketController : ApiController
{
//websocket列表,用于记录在线websocket链接
private static List<UserWebSocket> webSockets = new List<UserWebSocket>();
[HttpGet]
[Route("Connect")]
public HttpResponseMessage Connect()
{
//在服务器端接受Web Socket请求,传入的函数作为Web Socket的处理函数,待Web Socket建立后该函数会被调用,在该函数中可以对Web Socket进行消息收发
HttpContext.Current.AcceptWebSocketRequest(ProcessRequest);
return Request.CreateResponse(HttpStatusCode.SwitchingProtocols); //构造同意切换至Web Socket的Response.
}
public async Task ProcessRequest(AspNetWebSocketContext context)
{
var socket = context.WebSocket; //传入的context中有当前的web socket对象
//进入一个无限循环,当web socket close是循环结束
while (true)
{
var byte_length = 20971520;
var buffer = new ArraySegment<byte>(new byte[byte_length]);
//对websocket进行异步接收数据
var receivedResult = await socket.ReceiveAsync(buffer, CancellationToken.None);
//信息接收,我这边定义的消息结构为 userid:toUserid:content
string recvMsg = Encoding.UTF8.GetString(buffer.Array, 0, receivedResult.Count);
var msg = JsonConvert.DeserializeObject<SocketMsg>(recvMsg);
System.Threading.Thread.Sleep(10);
if (receivedResult.MessageType == WebSocketMessageType.Close)
{
if (msg == null)
{
break;
}
//如果连接已关闭,则删除记录
await socket.CloseAsync(WebSocketCloseStatus.Empty, string.Empty, CancellationToken.None); //如果client发起close请求,对client进行ack
webSockets.Remove(webSockets.FirstOrDefault(p => p.UserId == msg.userid));
break;
}
if (socket.State == WebSocketState.Open)
{
string message = "";
//此处将web socket对象加入一个静态列表中
var newWebsocket = webSockets.FirstOrDefault(p => p.UserId == msg.userid);
if (newWebsocket == null)
{
webSockets.Add(new UserWebSocket
{
UserId = msg.userid,
WebSocket = socket
});
}
else
{
newWebsocket.WebSocket = socket;
}
//组装返回的消息
message = JsonConvert.SerializeObject(msg); //content;
var recvBytes = Encoding.UTF8.GetBytes(message);
var sendBuffer = new ArraySegment<byte>(recvBytes);
//消息处理判断,也就是一开始进行连接的时候数据为空,我们不会发送数据到目标WebSocket
if (msg.msg != null)
{
if (msg.msg.ToString() != "__loop__" || msg.msg.ToString() != "_*_success_*_")
{
var toUser = GetOpenUserList();
foreach (var item in toUser)
{
var r = RemoveUser(item);
if (!r)
{
continue;
}
if (item.UserId == msg.touser)
{
try
{
//判断用户连接状态
if (item.WebSocket.State == WebSocketState.Open)
{
//消息发送给目标websocket
await item.WebSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
else
{
webSockets.Remove(item);
}
}
catch (WebSocketException e)
{
webSockets.Remove(item);
}
}
}
}
else
{
recvBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg));
sendBuffer = new ArraySegment<byte>(recvBytes);
var toWebSocket = webSockets.FirstOrDefault(p => p.UserId == msg.userid);
if (toWebSocket != null)
{
try
{
//消息发送给目标websocket
await toWebSocket.WebSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
catch (WebSocketException e)
{
webSockets.Remove(toWebSocket);
}
}
}
}
}
}
}
/// <summary>
/// 删除无效用户
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
public bool RemoveUser(UserWebSocket user)
{
try
{
var a = user.WebSocket.State;
return true;
}
catch (Exception ex)
{
webSockets.Remove(user);
return false;
}
}
/// <summary>
/// 获取有效的用户
/// </summary>
/// <param name="users"></param>
/// <returns></returns>
public List<UserWebSocket> GetOpenUserList()
{
List<UserWebSocket> userlist = new List<UserWebSocket>();
foreach (var i in webSockets)
{
try
{
var a = i.WebSocket.State;
userlist.Add(i);
}
catch (Exception ex)
{
continue;
}
}
return userlist;
}
}
public class UserWebSocket
{
public string UserId { get; set; }
public WebSocket WebSocket { get; set; }
}
public class SocketMsg
{
/// <summary>
/// 发送人id/用户id
/// </summary>
public string userid { get; set; }
/// <summary>
/// 接收人id
/// </summary>
public string touser { get; set; }
/// <summary>
/// 消息内容
/// </summary>
public object msg { get; set; }
}
}
C# WebApi WebSocket,C# WebApi 即时聊天
最新推荐文章于 2024-07-03 23:21:14 发布