1. 引入

1.1. koa + socket.io

const Koa = require('koa')
const app = new Koa()
const serve = require('koa-static')
const fs = require('fs')
app.use(serve('public'))  // static
// socket.io listen
const server = require('http').Server(app.callback())
const io = require('socket.io')(server)
server.listen(8080)
// socket.io logic
// ...
// ...

1.2. client

cdn:

<script src="https://cdn.bootcss.com/socket.io/2.0.4/socket.io.slim.js"></script>

connect:

let broadcast = io.connect('http://localhost:8080')

2. demo

2.1. broadcast

// server
io.on('connection', (socket) => {
    socket.broadcast.emit('user connected') // 除了当前socket之外 都会触发 user connected
})

// client
// broadcast
broadcast.on('user connected', () => {
    message.innerHTML = 'new user'
})

2.2. send-message

// server
io.on('connection', (socket) => {
    socket.on('message', function (msg) { // send(emit) message(listener)
        console.log(msg) // hi
    })
})

// client
broadcast.send('hi') // send(emit) message(listener)

2.3. emit-on-callback

let chat = io.of('/chat').on('connection', (socket) => {
    usercount++
    chat.emit('usercount', { msg: usercount }) // chat public emit
    socket.on('messagetoserver', (data, callback) => { // on
        socket.emit('messagetoclient', {
            msg: data.msg.toUpperCase(),
            username: 'server'
        }) // socket private emit
        callback('已收到') // callback
    })
})

2.4. namespace

// server
let news = io.of('/news').on('connection', (socket) => {
    // socket ...
})
let chat = io.of('/chat').on('connection', (socket) => {
    // socket ...
})

// client
let chat = io.connect('http://localhost:8080/chat')
let news = io.connect('http://localhost:8080/news')
// ...

完整代码

server:

const Koa = require('koa')
const app = new Koa()
const serve = require('koa-static')
const fs = require('fs')

app.use(serve('public'))  // static

// socket.io listen
const server = require('http').Server(app.callback())
const io = require('socket.io')(server)

server.listen(8080)

// socket.io logic

let usercount = 0

// broadcast
io.on('connection', (socket) => {
    socket.broadcast.emit('user connected') // 除了当前socket之外 都会触发 user connected
    socket.on('message', function (msg) { // send(emit) message(listener)
        console.log(msg)
    })
})

let chat = io.of('/chat').on('connection', (socket) => {
    // connect usercount
    usercount++
    chat.emit('usercount', { msg: usercount }) // public message
    socket.on('messagetoserver', (data, callback) => {
        socket.emit('messagetoclient', { msg: data.msg.toUpperCase(), username: 'server' })
        callback('已收到')
    })

    // disconnect usercount
    socket.on('disconnect', function () {
        usercount--
        chat.emit('usercount', { msg: usercount })
    })
})

let news = io.of('/news').on('connection', (socket) => {
    let newsInterval = setInterval(() => {
        socket.emit('news', { msg: 'news from ' + Date.now() })
    }, 1000)

    // disconnect
    socket.on('disconnect', () => {
        clearInterval(newsInterval)
    })
})

client:

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

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>index</title>
        <script src="https://cdn.bootcss.com/socket.io/2.0.4/socket.io.slim.js"></script>
    </head>

    <body>
        <div id="message"></div>
        <div id="thenews">news...</div>
        <div>当前在线人数
            <span id="count">0</span>
        </div>
        <input type="text" id="input">
        <ol id="msg"></ol>
        <script>
            let chat = io.connect('http://localhost:8080/chat')
            let news = io.connect('http://localhost:8080/news')
            let broadcast = io.connect('http://localhost:8080')

            let input = document.getElementById('input')
            let msg = document.getElementById('msg')
            let thenews = document.getElementById('thenews')
            let message = document.getElementById('message')

            // broadcast
            broadcast.on('user connected', () => {
                message.innerHTML = 'new user'
                setTimeout(() => {
                    message.innerHTML = ''
                }, 2000);
            })
            broadcast.send('hi') // send(emit) message(listener)

            // usercount
            chat.on('usercount', (data) => {
                document.getElementById('count').innerHTML = data.msg
            })
            // send message
            input.addEventListener('change', (e) => {
                let list = document.createElement('li')
                list.innerHTML = 'me: ' + e.target.value
                msg.appendChild(list)
                chat.emit('messagetoserver', { msg: e.target.value }, (callbackdata) => {
                    e.target.value = ''
                    list.innerHTML += ' -> ' + callbackdata
                })
            })
            // get message
            chat.on('messagetoclient', (data) => {
                let list = document.createElement('li')
                list.innerHTML = data.username + ': ' + data.msg
                msg.appendChild(list)
                list = null
            })

            // ...
            news.on('news', (data) => {
                thenews.innerHTML = data.msg
            })
        </script>
    </body>

    </html>

JS菌
6.4k 声望2k 粉丝

引用和评论

0 条评论