C# 实现WEBSOCKET聊天应用示例

2021-02-15 15:16

阅读:714

  

ValueWebSocket.cs
public class ValueWebSocket
{
// WebSocket服务端
private ValueServer server;
// 解析协议
private ValueProtocol valueProtocol;
// 管理在线用户
private SessionManager sessionManager;

public ValueWebSocket(String ipAddress, Int32 port)
{
valueProtocol = new ValueProtocol();
sessionManager = new SessionManager();

server = new ValueServer(ipAddress, port, Encoding.UTF8);
server.OnReceive += new ValueHelper.ValueSocket.Infrastructure.ReceiveHandler(server_OnReceive);
}

private void server_OnReceive(ValueHelper.ValueSocket.SocketEvents.ReceiveEventArgs e)
{
// 分析用户是否已存在
if (sessionManager.CheckSessionExist(e.Socket))
{
Message message = valueProtocol.Decode(e.Data);
if (message.header.Opcode == OperType.Close)
{
removeUser(e.Socket);
}
if (message.header.Opcode == OperType.Text)
{
String msg = message.Data.ToString();
execMsg(e.Socket, msg);
}
}
else
{
// 用户不存在则添加用户
// 并发送握手信息与客户端建立连接
String request = Encoding.UTF8.GetString(e.Data);
Byte[] response = valueProtocol.GetResponse


评论


亲,登录后才可以留言!