We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
npm install --save socket.io
├── index.js ├── node_modules ├── package.json └── views └── index.html
./index.js
const http = require('http'); const fs = require('fs'); const socketIO = require('socket.io'); const server = http.createServer((req, res) => { let html = fs.readFileSync('./views/index.html'); res.end(html); }).listen(3000,'127.0.0.1', () => { console.log('socket.io server is running at http://127.0.0.1:3000/'); }); // socket io 操作 const io = socketIO.listen(server); io.sockets.on('connection', (socket) => { console.log('socket.io connected'); // 监听socket断开事件 socket.on('disconnect',() => { console.log('socket.io disconnected'); }); // 轮询进行 服务端推送 自定义事件 let serverNum = 0; setInterval(() => { serverNum ++; socket.emit('server.message', { serverNum: serverNum }); }, 1000); // 监听客户端推送 自定义事件 socket.on('client.message', (data) => { console.log('[client.message]', data) }); });
./views/index.html
<!DOCTYPE html> <html> <head> <title>demo</title> </head> <body> <h1>socket.io demo</h1> <script src="/socket.io/socket.io.js"></script> <script> const socket = io.connect('http://127.0.0.1:3000'); // 监听 socket 连接事件 socket.on('connection', () => { console.log('socket.io connected'); socket.open(); }); // 监听 socket 断开事件 socket.on('disconnect',() => { console.log('socket.io disconnected'); socket.close(); }); let clientNum = 0; // 轮询 推送客户端信息 到服务端 setInterval(() => { clientNum ++; socket.emit('client.message', { clientNum: clientNum }); }, 1000); // 监听服务端 自定义信息事件 socket.on('server.message', (data) => { console.log('[server.message]', data) }); </script> </body> </html>
node index.js
The text was updated successfully, but these errors were encountered:
No branches or pull requests
安装socket.io
demo目录
服务端代码
./index.js
客户端代码
./views/index.html
启动服务
The text was updated successfully, but these errors were encountered: