C#WebSocket服务端,js充当WebSocket客户端

本文介绍了如何使用C#开启WebSocket服务端,借助Fleck库,并用JavaScript作为客户端进行连接。文章提供了详细步骤,包括服务端设置、引入dll、客户端JS代码示例,以及Git仓库和dll下载链接。强调了服务端类需继承特定基类,方法返回特定结果,并且不支持方法重载。
摘要由CSDN通过智能技术生成


C#开启WebSocket服务端,js开启客户端

1.效果演示

Socket服务端实现效果(高清)


2.引入相关dll

程序使用的NuGet插件
Fleck(1.2.0.0)
Newtonsoft.Json(13.0.0.0)
程序使用的自定义实体
PublicEntity

示例服务端:

public class ScreenAndWeight : SocketServer.WebSocketAction.WebSocketServerActionBase
    {
        /// <summary>
        /// 初始化屏幕
        /// </summary>
        /// <param name="type">0不带数据1带数据</param>
        /// <returns></returns>
        public SocketServer.SocketResult.ISocketResult Load(int type = 0)
        {
            return RSuccess("操作成功");
        }
    }

3. js开启WebSocket客户端

代码如下(直接复制就能用):

/** websocket对象 */
let websocket = null;
/**是否链接到Socket */
let IsOpen = false;

/**
 * 获取Socket,null表示浏览器不支持
 * @param {string} url 链接 示例"ws://127.0.0.1:8888","wss://127.0.0.1:8888"
 * @param {Function} MessageEvent 服务端发送消息时回调函数 带有一个参数evt.data
 * @param {Function} OpenEvent 成功链接到服务端的回调函数 无参
 * @param {Function} CloseEvent 关闭链接时回调函数 无参
 * @param {Function} ErrorEvent 出现异常时回调函数 带有一个参数evt
 */
function GetSocket(url, MessageEvent = null, OpenEvent = null, CloseEvent = null, ErrorEvent = null) {
    let socket
    if ('WebSocket' in window) {
        socket = new WebSocket(url);
    } else if ('MozWebSocket' in window) {
        socket = new MozWebSocket(url);
    } else {
        alert('不支持当前浏览器!');
        socket = null
        return socket
    }
    //注册各类回调
    socket.onopen = function (evt) {
        IsOpen = true
        if (OpenEvent == null) {
            console.log("服务端链接成功!")
        } else {
            OpenEvent();
        }
    }
    socket.onclose = function (evt) {
        socket = null
        IsOpen = false
        if (CloseEvent == null) {
            console.log("服务端链接关闭!")
        } else {
            CloseEvent();
        }
    }
    socket.onerror = function (evt) {
        if (ErrorEvent == null) {
            console.log("链接Socket出现异常!")
        } else {
            ErrorEvent(evt);
        }
    }
    socket.onmessage = function (evt) {//接收服务端数据返回
        if (MessageEvent == null) {
            console.log("服务端消息:  " + evt.data)
        } else {
            MessageEvent(evt.data);
        }
    }
    return socket
}

/**
 * 开启默认的Socket(websocket)
 * @param {string} url 链接 示例"ws://127.0.0.1:8888","wss://127.0.0.1:8888"
 * @param {Function} MessageEvent 服务端发送消息时回调函数 带有一个参数evt.data
 * @param {Function} OpenEvent 成功链接到服务端的回调函数 无参
 * @param {Function} CloseEvent 关闭链接时回调函数 无参
 * @param {Function} ErrorEvent 出现异常时回调函数 带有一个参数evt
 */
function SocketStart(url, MessageEvent = null, OpenEvent = null, CloseEvent = null, ErrorEvent = null) {
    websocket = GetSocket(url, MessageEvent, OpenEvent, CloseEvent, ErrorEvent)
}

/**
 * 发送消息(对默认的socket发送消息--websocket)
 * @param {string|ArrayBuffer} message 消息信息 (byte[]或者字符串)
 */
function SocketSend(message) {
    if (!IsOpen) {
        return
    }
    websocket.send(message);
}

/**
 * 关闭链接(关闭默认的socket发送消息--websocket)
 */
function SocketClose() {
    if (!IsOpen) {
        return
    }
    websocket.close();
}


4. git地址

https://gitee.com/good-for-children/socket-server.git

5. dll下载地址

百度云链接(代码+dll):https://pan.baidu.com/s/1tLdweZM3luVrTKcBw4Fr1g?pwd=4jku
csdn链接(旧dll):https://download.csdn.net/download/m0_48365841/87698340

注意

1.WebSocket启动方式

var socketServer = new SocketServer.WebSocketServerStartHelper(“ws://127.0.0.1:9999”);
socketServer.SetType();
//socketServer.SetAssemblies()//加载程序集
//socketServer.SetTypes()//加载类型
socketServer.Start();

在代码里面执行上述模块即可
使用SetType、SetAssemblies、SetTypes进行加载相关的类以及方法
无论使用哪一种方法都要注意以下几点

1.加载的类必须继承SocketServer.WebSocketAction.WebSocketServerActionBase或SocketServer.WebSocketAction.IWebSocketServerAction

2.加载的类至少包含一个返回SocketServer.SocketResult.ISocketResult的方法如果不包含则不会加载类,即使这个类已经继承了相关基类

3.调用服务端方法

假如AClass继承了SocketServer.WebSocketAction.WebSocketServerActionBase
	其中有一个方法TestA()返回SocketServer.SocketResult.ISocketResult
		调用TestA示例:websocket.send("AClass/TestA");//websocket是网页的socket对象
	其中有一个方法TestB(int a,int b = 2)返回SocketServer.SocketResult.ISocketResult
		调用TestB示例:websocket.send("AClass/TestB?a=1&b=3");//websocket是网页的socket对象
		调用TestB示例:websocket.send("AClass/TestB?a=1");//websocket是网页的socket对象
		有默认值的可以省略,无默认值的必须指定值,否则调用不成功

4.加载的类不能同名(Type的Name不能相同)

5.不支持方法重载

6.所有加载成功的类都自带一个方法Cache

调用方法{ClassName}/Cache    {ClassName}换成相应类型名称
例如:websocket.send("AClass/Cache");//websocket是网页的socket对象

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值