[fix]Config创建默认配置文件的开关Runtime.CreateConfigOnMissing,仅需对自动创建生效,而不应该阻止用户主动Save
智能大石头 编写于 2024-08-09 00:30:41 石头 提交于 2024-08-10 14:22:24
X
using System;
using NewLife.Log;

namespace NewLife.Http
{
    /// <summary>WebSocket处理器</summary>
    public class WebSocketHandler : IHttpHandler
    {
        /// <summary>处理请求</summary>
        /// <param name="context"></param>
        public virtual void ProcessRequest(IHttpContext context)
        {
            var ws = context.WebSocket;
            ws.Handler = ProcessMessage;

        WriteLog("WebSocket连接 {0}", context.Connection?.Remote);
    }

    /// <summary>处理消息</summary>
    /// <param name="socket"></param>
    /// <param name="message"></param>
    public virtual void ProcessMessage(WebSocket socket, WebSocketMessage message)
    {
        var remote = (socket.Context?.Connection?.Remote) ?? throw new ObjectDisposedException(nameof(socket.Context));

        //var remote = socket.Context.Connection.Remote;
        var msg = message.Payload?.ToStr();
        if (msg == null) return;

        switch (message.Type)
        {
            case WebSocketMessageType.Text:
                WriteLog("WebSocket收到[{0}] {1}", message.Type, msg);
                // 群发所有客户端
                socket.SendAll($"[{remote}]说,{msg}");
                break;
            case WebSocketMessageType.Close:
                WriteLog("WebSocket关闭[{0}] [{1}] {2}", remote, message.CloseStatus, message.StatusDescription);
                break;
            case WebSocketMessageType.Ping:
            case WebSocketMessageType.Pong:
                WriteLog("WebSocket心跳[{0}] {1}", message.Type, msg);
                break;
            default:
                WriteLog("WebSocket收到[{0}] {1}", message.Type, msg);
                break;
        }
    }

        private void WriteLog(String format, params Object[] args) => XTrace.WriteLine(format, args);
    }
}