nodejs 集成 Socket.io服务
npm install -D socket.io
新建一个socketRouter.js文件。写入如下内容
function registerSocket(app) { var server = require('http').createServer(app); //服务器监听事件 server.on('listening', function () { console.log("server listening:" + server.address().port); }); //服务器错误事件 server.on("error", function (exception) { console.log("server error:" + exception); }); //引入socket.io var io = require('socket.io')(server, { //处理跨域问题 cors: { origin: "*", methods: ["PUT", "POST", "GET", "DELETE", "OPTIONS"], allowedHeaders: "*", credentials: true }, pingTimeout: 15000, pingInterval: 5000 }); io.on('connection', function (socket) { console.log('服务器建立连接了'); // 创建房间 socket.on('createroom', req => { let roomid = req.roomid; console.log('连接服务房间号:', roomid); socket.join(roomid); //发送消息 socket.to(roomid).emit('message', { msg: roomid }); //发送消息 // socket.emit('message', { // msg: '创建房间' + roomid + '成功' // }) socket.emit('message', {Code: 1,Message:"服务器信息"}, data => { console.log("received message callback from client", data); }); socket.emit('hello', {msg:"hello text"}); }); // 接受消息 socket.on('sayMsg', req => { let roomid = req.roomid let msg = req.msg console.log("房间号:", roomid); console.log("接收到的信息:", msg); socket.to(roomid).emit('message', { roomid: roomid, msg: msg }) }); socket.on("ack", (name, fn) => { fn({ result: true, message: `ack(${name})` }); }); //数据错误事件 socket.on('error', function (exception) { console.log('socket error:' + exception); socket.end(); }); // 连接断开,如关闭页面时触发 socket.on('disconnect', function () { console.log('已断开链接'); delete global.clients[global.clientIds[socket.id]]; delete global.clientIds[socket.id]; }); //客户端关闭事件 socket.on('close', function (data) { console.log('close: ' + socket.remoteAddress + ' ' + socket.remotePort); }); global.socket = socket; }); //设置统一的端口号(注:要把bin目录下www文件的端号注册给注释) const port = process.env.PORT || 3000; server.listen(port, () => console.log(`Listening on port ${port}`)); } module.exports = registerSocket;
www文件端口号注释
然后在app.js文件中引入socketRouter.js文件然后进行注册
引入
注册:
C# 客户端:
引入SocketIOClient的命名空间
var client = new SocketIO("http://192.168.0.197:3000/", new SocketIOOptions { EIO = 4 }); //连接成功 client.OnConnected += async (sender, e) => { string id = System.Guid.NewGuid().ToString("N"); //创建房间号 await client.EmitAsync("createroom", new { roomid = id }); //监听服务端下发消息 client.On("message", response => { Debug.WriteLine($"服务端下发信息:{response}"); }); await client.EmitAsync("sayMsg", new { roomid = id, msg="您来了,欢迎您!" }); }; client.OnDisconnected += (sender, e) => { //连接断开时 }; await client.ConnectAsync();
启动nodejs socket.io服务端
启动C#客户端然后看服务端输出
js端使用:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> input { background-color: #fff; background-image: none; border-radius: 4px; border: 1px solid #bfcbd9; box-sizing: border-box; color: #1f2d3d; font-size: inherit; height: 40px; line-height: 1; outline: 0; padding: 3px 10px; } .el-button--primary { color: #fff; background-color: #20a0ff; border-color: #20a0ff; } .el-button { display: inline-block; line-height: 1; white-space: nowrap; cursor: pointer; background: #00aac5; border: 1px solid #c4c4c4; color: #fff; margin: 0; padding: 10px 15px; border-radius: 4px; outline: 0; text-align: center; } </style> </head> <body> <div> <div id="content"> </div> </div> <div> <input type="text" id="input"> <ul> <li> <button class="el-button el-button--primary el-button--large" type="button" onclick="startConnect()"><span>开始连接</span></button> <button class="el-button el-button--primary el-button--large" type="button" onclick="createRoom()"><span>创建房间号</span></button> <button class="el-button el-button--primary el-button--large" type="button" onclick="sendMsg()"><span>测试发送消息</span></button> <button class="el-button el-button--primary el-button--large" type="button" onclick="close()"><span>断开连接</span></button> </li> </ul> </div> <!-- 注意,这里的静态资源一定要是绝对路径,否则会被拦截 --> <script src="./static/socket.io.js"></script> <script> var socket let roomid = new Date().getTime() // 开始连接 function startConnect() { socket = io.connect('ws://192.168.99.215:3000'); console.log("连接成功", socket); createRoom (); } // // 创建房间号 function createRoom() { console.log(roomid) socket.emit('createroom', { roomid: roomid }); } // 向指定的房间号发送消息 function sendMsg() { // 获取yinput 表单里面的值 let t = document.getElementById('input').value if (!t) return let html = document.createElement('p') html.innerHTML = `你细声说:<span>${t}</span>` document.getElementById('content').appendChild(html) socket.emit('plateInfo', { roomid: roomid, msg: t }); } function close() { let t = "断开"; socket.emit('disconnect', { roomid: roomid, msg: t }); } </script> </body> </html>
注:要引入客户端的js文件
评论区