服务端(node)
var express = require('express');
var app = express();
var server = require('http').Server(app);
var ws = require('socket.io')(server);
//将socket 服务器和express 进行结合
app.use(express.static(__dirname + '/client'))
// 客户端连接
ws.on('connection', function (client) {
client.emit('hehe','欢迎光临') //发送呵呵事件,该事件数据为'欢迎光临'
client.on('haha',(msg)=>{
console.log('haha'+msg)
})
});
server.listen(8081, '0.0.0.0');
客户端(H5)
<!DOCTYPE html>
<html lang="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>socket.io</title>
<script src="socket.io.js" charset="utf-8"></script>
</head>
<body>
<script>
var socket = io.connect('http://10.9.68.149:8081');
//连接服务器
socket.on('hehe', function(msg){
console.log('hehe'+msg)
})
socket.emit('haha','我来了')
</script>
</body>
</html>
ps
1.和websocket相比,需要在客户端引入socket.io.js(该文件在服务端npm install的时候,在node_modules里socket.io-client里找)