WebSocket:实时通讯-方法2

1.引言

socket.io实现websocket通讯

2.server端

参考文档:

https://socket.io/docs/server-api/

https://github.com/socketio/socket.io

npm install socket.io
npm install express
const express = require('express')
const http = require('http')
const path = require('path')
const fs = require('fs')

const app = express()

app.use('/static',express.static(path.join(__dirname,'public')))

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'views', 'index.html'))
})

const server = http.createServer(app)


server.listen(3000, function () {
    console.log('server is running on port:3000')
})


const io = require('socket.io')(server)

io.on('connection',socket=>{
    console.log('connection----------------->')
    socket.on('message',msg=>{
        console.log(msg)
        io.emit('message',msg)
    })
    socket.on('disconnect',()=>{
        console.log('user disconnected-----------')
    })
})

3.client端

参考文档:

https://socket.io/docs/client-api/

https://github.com/socketio/socket.io-client

本地文件:node_modules/socket.io-client/dist/socket.io.js

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #ta {
            width: 100vw;
        }
    </style>
    <script src="/static/js/socket.io.js"></script>
</head>

<body>
    <h1>Socket IO Test</h1>
    <div>
        <textarea name="" id="ta" cols="30" rows="10"></textarea>
        <button id="btn_connect">connect</button>
        <button id="btn_send">send</button>
    </div>
    <script>
        const btn1 = document.querySelector('#btn_connect')
        const btn2 = document.querySelector('#btn_send')
        const ta = document.querySelector('#ta')
        let socket = null
        btn1.addEventListener('click', function () {
            socket = io('http://localhost:3000')
            socket.on('connect', () => {
                console.log('connection------>')
                ta.innerHTML = "connection------>"
            })
            socket.on('message', data => {
                console.log(data)
                ta.innerHTML += data.msg + '\n'
            })
            socket.on('disconnect', () => {
                console.log('disconnect------->')
            })
        })
        btn2.addEventListener('click', function () {
            socket.send({
                msg: 'hello world'
            })
        })
    </script>
</body>

</html>

4.扩展

登录与注销:

//监听新用户登录
socket.on('login', function(o){
    console.log(o, 'login');
  });
  //监听用户退出
socket.on('logout', function(o){
      console.logo(o, 'logout');
});

发送登录信息:

//告诉服务器端有用户登录
socket.emit('login', {userid:this.userid, username:this.username});

发送信息:

var obj = { userid: this.userid,username: this.username, content:content};
socket.emit('message', obj);

//也可直接send
socket.send(obj)

监听消息发送:

socket.on('message' , function(obj){
            console.log(obj,' message')
}}

权限和认证:

每个连接的socket.id都不同,可以根据socket.id和token控制

给指定用户发送消息:

io.on('connection', (socket) => {

  // to one room
  socket.to('others').emit('an event', { some: 'data' });

  // to multiple rooms
  socket.to('room1').to('room2').emit('hello');

  // a private message to another socket
  socket.to(/* another socket id */).emit('hey');

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.
});
学习更多知识,加QQ群:1098090823
威武网 » WebSocket:实时通讯-方法2

提供最优质的资源集合

立即查看 了解详情