服务端代码/***/
// 服务端代码 var express = require('express'); var app = express(); var path = require('path'); var server = require('http').createServer(app); var io = require('socket.io')(server); var port = process.env.PORT || 5000; server.listen(port, () => { console.log('Server listening a1111 port %d', port); }); io.on('connection', (socket) => { socket.on('add user', (username) => { console.log(username) }); });
客户端代码/****/使用socket.io/2.2.0
var socket = io(); socket.on('login', (data) => { console.log('login') socket.emit('add user', {1:2}); }); socket.on('disconnect', (data) => { console.log('disconnect') socket.emit('add user', {1:2}) }); socket.on('connect', (data ) => { console.log('connect') socket.emit('add user', {1:2}) });
配上nginx的配置
location /socket { #此处改为 socket.io 后端的 ip 和端口即可 proxy_pass http://xxx.xxx.xx.xx:5000; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; }