首先在服务端下载依赖
npm install socket.io@2.0.4 socket.io版本过高会出现问题
npm install express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const ws = require('socket.io')(server);
//将socket 服务器和express进行结合 这样就不用起两个服务了
app.use(express.static(__dirname + './client'))
//客户端连接
ws.on('connection',function(client){
client.emit('hehe','欢迎光临 socket.io') //emit 触发客户端注册的hehe事件 必须对应
client.on('haha',(msg)=>{
console.log(msg)
})
})
server.listen(8081, '192.168.1.19');//如果是'0.0.0.0'允许所以端口访问
客户端
首先要引用客户端所需要的js文件
链接服务器这里用的不是WebSocket协议,用的是http协议
WebSocket的传值是通过onmessage和message来实现的
socket.io是通过emit事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./node_modules/socket.io-client/dist/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect('http://192.168.1.19:8081');
//链接服务器
socket.on('hehe',function(msg){
console.log(msg)
})
socket.emit('haha', '你好啊')
</script>
</body>
</html>