c#基於supersocket的簡單websocket服務端收發消息實現

using log4net;
using SuperSocket.SocketBase;
using SuperSocket.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SupersocketServer
{
class Program {
private static readonly ILog infoLogger = LogManager.GetLogger("Logger");
static void Main(string[] args)
{

WebSocketServer ws = new WebSocketServer();
ws.NewMessageReceived += Ws_NewMessageReceived;//當有信息傳入時
ws.NewSessionConnected += Ws_NewSessionConnected;//當有用戶連入時
ws.SessionClosed += Ws_SessionClosed;//當有用戶退出時
ws.NewDataReceived += Ws_NewDataReceived;//當有數據傳入時
if (ws.Setup(10086))//綁定端口
ws.Start();//啓動服務
infoLogger.Info("服務已啓動");
Console.ReadKey();
}
public static List<WebSocketSession> sessionList = new List<WebSocketSession>();
private static void Ws_NewDataReceived(WebSocketSession session, byte[] value)
{
string str = Encoding.UTF8.GetString(value);
infoLogger.InfoFormat("數據傳入 id:{0},value:{1}", session.SessionID, str);
}

private static void Ws_SessionClosed(WebSocketSession session, CloseReason value)
{
sessionList.Remove(session);
infoLogger.InfoFormat("用戶退出:{0},value:{1}", session.SessionID, value);
}

private static void Ws_NewSessionConnected(WebSocketSession session)
{
sessionList.Add(session);
infoLogger.InfoFormat("用戶連入:" + session.SessionID);
}

private static void Ws_NewMessageReceived(WebSocketSession session, string value)
{
infoLogger.InfoFormat("接收消息 id:{0},value:{1}", session.SessionID, value);
if (value=="Hello")
{
//模擬心跳包
sessionList.ForEach(o => { o.Send("你好"); });
}
}
}
}
相關文章
相關標籤/搜索