fleck 客户端_Fleck学习笔记

fleck 客户端_Fleck学习笔记usingFleck;usingNewtonsoft.Json;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;namespaceWebSocketService.App_Start{publicclassFleckHelper{privatestaticListallSockets...

usingFleck;usingNewtonsoft.Json;usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;namespaceWebSocketService.App_Start

{public classFleckHelper

{private static List allSockets = new List();private static Dictionary socketDic = new Dictionary();///

///WebSocket初始化///

public static voidWebSocketInit()

{var server = new WebSocketServer("ws://0.0.0.0:8181");//此处端口随意指定,但是不能被占用

server.Start(socket =>{

socket.OnOpen= () =>{//Console.WriteLine("Open!");//allSockets.Add(socket);//socketDic.Add(socket.ConnectionInfo.Id.ToString(), socket);//此处想要存储指定的key值,但是无法接收指定参数,仅供测试玩

var key = socket.ConnectionInfo.Path.Substring(1);if (!socketDic.Keys.Contains(key))

{

socketDic.Add(key, socket);//此处想要存储指定的key值,但是无法接收指定参数,仅供测试玩

}else{if (socketDic[key] != null)

{

socketDic[key].Close();

}

socketDic[key]=socket;

}

};

socket.OnClose= () =>{//Console.WriteLine("Close!");//allSockets.Remove(socket);//socketDic.Remove(socket.ConnectionInfo.Id.ToString());//此处想要删除指定的key值,但是无法接收指定参数,仅供测试玩

var key = socket.ConnectionInfo.Path.Substring(1);

socketDic.Remove(key);//此处想要删除指定的key值,但是无法接收指定参数,仅供测试玩

};

socket.OnMessage= message =>{//Console.WriteLine(message);//allSockets.ToList().ForEach(s => s.Send("Echo: " + message));

};

});

}///

///消息发送///

/// 自定义json字符串

public static void Send(stringmessage)

{try{var msgInfo = JsonConvert.DeserializeObject(message);var toUser =msgInfo.ToUser;var msg =msgInfo.Msg;if (!string.IsNullOrWhiteSpace(toUser))//已指定接收人

{if (socketDic.Keys.Contains(toUser))//确认是否有接收人的WebSocket

{

socketDic[toUser].Send(msg);//发送给指定接收人

}

}else{

socketDic.Values.ToList().ForEach(p=> p.Send(msg));//未指定接收人全部发送

}

}catch(Exception)

{throw;

}

}///

///自定义消息类///

public classMessageInfo

{///

///接收人///

public string ToUser { get; set; }///

///发送信息///

public string Msg { get; set; }

}

}

}

架构君码字不易,如需转载,请注明出处:https://javajgs.com/archives/209946
0

发表评论