zoukankan      html  css  js  c++  java
  • 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("你好"); });
    }
    }
    }
    }
    

      

    -------------------------------------------

    学而不思则罔,思而不学则殆

    你好,我是【咬轮猫】

    -------------------------------------------

  • 相关阅读:
    127.0.0.1
    【转】linux查看及修改文件权限以及相关
    【转】为什么要进行傅立叶变换?傅立叶变换究竟有何意义?如何用Matlab实现快速傅立叶变换?
    ADO.NET类库与SQL相关的知识梳理
    【转】应用软件系统架构设计的“七种武器”
    CPoint、CSize、CRect类
    【转】关于int、float、double一些知识的整理
    C# 实现屏幕键盘
    如何在C#中读写INI文件
    TreeView复选框选择逻辑判断
  • 原文地址:https://www.cnblogs.com/Hero-/p/9713210.html
Copyright © 2011-2022 走看看