小DEMO快速开始一个socket.io项目

Posted JS菌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小DEMO快速开始一个socket.io项目相关的知识,希望对你有一定的参考价值。

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 listenconst 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

// serverio.on('connection', (socket) => {
socket.broadcast.emit('user connected') // 除了当前socket之外 都会触发 user connected})// client// broadcastbroadcast.on('user connected', () => {
message.innerhtml = 'new user'})

2.2. send-message

// serverio.on('connection', (socket) => {
socket.on('message', function (msg) { // send(emit) message(listener)console.log(msg) // hi})
})// clientbroadcast.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 emitsocket.on('messagetoserver', (data, callback) => { // onsocket.emit('messagetoclient', {
msg: data.msg.toUpperCase(),
username: 'server'}) // socket private emitcallback('已收到') // callback})
})

2.4. namespace

// serverlet news = io.of('/news').on('connection', (socket) => {// socket ...})let chat = io.of('/chat').on('connection', (socket) => {// socket ...})// clientlet 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 listenconst server = require('http').Server(app.callback())const io = require('socket.io')(server)

server.listen(8080)// socket.io logiclet usercount = 0// broadcastio.on('connection', (socket) => {
socket.broadcast.emit('user connected') // 除了当前socket之外 都会触发 user connectedsocket.on('message', function (msg) { // send(emit) message(listener)console.log(msg)
})
})let chat = io.of('/chat').on('connection', (socket) => {// connect usercountusercount++
chat.emit('usercount', { msg: usercount }) // public messagesocket.on('messagetoserver', (data, callback) => {
socket.emit('messagetoclient', { msg: data.msg.toUpperCase(), username: 'server' })
callback('已收到')
})// disconnect usercountsocket.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)// disconnectsocket.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')// broadcastbroadcast.on('user connected', () => { message.innerHTML = 'new user'setTimeout(() => { message.innerHTML = ''}, 2000); }) broadcast.send('hi') // send(emit) message(listener)// usercountchat.on('usercount', (data) => {document.getElementById('count').innerHTML = data.msg })// send messageinput.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 messagechat.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>