快捷搜索: 王者荣耀 脱发

WebSocketServer 服务端 c#

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Newtonsoft.Json;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace PrintPlugin
{
          
   
    public partial class Form_Main : Form
    {
          
   
        public Form_Main()
        {
          
   
            InitializeComponent();
        }

        private void Form_Main_Load(object sender, EventArgs e)
        {
          
   
            var wssv = new WebSocketServer(54321);
            wssv.AddWebSocketService<PrintServer>("/PrintServer");//添加服务侦听,第一个是类。第二个是调用的接口
            wssv.Start();
            Console.WriteLine("打印服务运行中...");
     
           // wssv.Stop();
        }
        class PrintServer : WebSocketBehavior
        {
          
   
            static Dictionary<string, string> dClientAll = new Dictionary<string, string>();
            protected override void OnOpen()
            {
          
   
                dClientAll.Add(base.Context.SecWebSocketKey, base.Context.UserEndPoint.ToString());
                Console.WriteLine("连接打开" + dClientAll[base.Context.SecWebSocketKey] + "|" + DateTime.Now.ToString());
                base.OnOpen();
            }
            protected override void OnMessage(MessageEventArgs e)
            {
          
   
                var data = e.Data + "|" + DateTime.Now.ToString();
                Console.WriteLine("接收数据" + dClientAll[base.Context.SecWebSocketKey] + "|" + data);
                var retjson = JsonConvert.SerializeObject(new {
          
    code = 200, msg = data });
                Send(retjson);

            }
            protected override void OnClose(CloseEventArgs e)
            {
          
   
                Console.WriteLine("连接关闭" + dClientAll[base.Context.SecWebSocketKey] + "|" + DateTime.Now.ToString());
                base.OnClose(e);
            }
            protected override void OnError(ErrorEventArgs e)
            {
          
   
                Console.WriteLine("错误信息" + dClientAll[base.Context.SecWebSocketKey] + "|" + DateTime.Now.ToString());
                base.OnError(e);
            }
        }
    }
}
经验分享 程序员 微信小程序 职场和发展