socket.io笔记,socket跨域,命名空间、node作为服务器

本文章仅作为作者笔记使用,不建议初学者作为资料翻阅

但作者建议:学习还是先翻看socket.io官方文档,看看,在浏览其他的(官方文档和学习中一定要仔细看版本差异)

官方文档:https://socket.io/

index.html客户端代码

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <!-- 4.0.1版本 ↓ 在项目node中没有配置相关静态访问资源,所以这个会报错404 GET http://localhost:3000/socket.io.js net::ERR_ABORTED 404 (Not Found)-->
    <!-- <script src="./socket.io.js"></script> -->

    <script>
    
        (function(){
            // var socket = io('http://127.0.0.1:3000/chat');
            var socket = io('http://127.0.0.1:3000');
            socket.emit('input','你好小可爱')
            socket.on('output',msg=>{
                console.log(msg,'还回来的数据')
            })
        })()
    </script>
  </head>
  <body>
      <h1>聊天的</h1>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

服务器端的代码:

var app = require('express')();
var http = require('http').createServer(app);
// {cors:true}为设置跨域
var io = require('socket.io')(http,{cors:true});

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});
/*
* 在此再说一遍内容 后端的socket用的版本(本文件用的4.0.1)一定保持一致,前台用的也应该为4.0.1
* 提示:2.x和4.x方式有点不同,至于2.x、3.x、4.x有啥区别大家可以自己研究
*/

// .of("/chat")  群发事件内容to('chat').
// socket.broadcast.emit('有用户连接');
// //这条信息会发送给除了当前socket的其他用户
// socket.broadcast.to(空间名).emit('有用户连接');  群发到那个明明空间中
io.of("/chat").on('connection', (socket) => {
    console.log('socket开始');
    socket.on('input',msg=>{
        console.log(msg,'------客户端发送的消息')
        // 子命名空间的发送事件应该是形参socket
        socket.emit('output','还给你发送的数据')
    })
    socket.on('disconnect',()=>{
        console.log('socket结束,监听事件销毁')
    })
});
// 主命名空间
io.on('connection', (socket) => {
    console.log('socket开始');
    socket.on('input',msg=>{
        console.log(msg,'------1')
        io.emit('output','12')
    })
    socket.on('disconnect',()=>{
        console.log('123')
    })
});
http.listen(3000, () => {
  console.log('listening on *:3000');
});

package.json文件

{
    "name": "socket-chat-example",
    "version": "0.0.1",
    "scripts": {
        "start": "nodemon ./index"
    },
    "description": "my first socket.io app",
    "dependencies": {
        "express": "^4.15.2",
        "nodemon": "^2.0.7",
        "socket.io": "^4.0.1"
    }
}

运行项目命令:

npm start

 目录截图:

原理图:

emit 发送数据

on接收数据内容

原文地址:https://www.cnblogs.com/enhengenhengNymph/p/14684508.html