1.快速配置一个nodejs server
- 安装 nodejs
- 安装express
npm install -g express
- 安装express-generator
npm install -g express-generator
- 通过express 自动生产nodejs server(这一步自动产生package.json等文件)
express my-node
- 安装socket.io
npm install socket.io
- 修改 /bin/www文件,加入如下代码
//创建socket
var socket = io.listen(server);
//添加连接监听
socket.on('connection', function(client){
//连接成功则执行下面的监听
client.on('message',function(event){
console.log('Received message from client!',event);
socket.emit('news', Date.now())
});
//断开连接callback
client.on('disconnect',function(){
console.log('Server has disconnected');
});
});
- 通过 npm start 运行服务端
- 配置client
编写一个新的页面,点击发送按钮既可以看到通信开始(不存在同源限制)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
</head>
<body>
<button id="test">发送</button>
</body>
<script>
var socket = io.connect('http://localhost:3000');
document.getElementById("test").onclick = handleClick;
function handleClick() {
socket.emit('message', Date.now());
}
socket.on('news', function (data) {
setTimeout(()=>{
console.log(data);
socket.emit('message', { my: data });
}, 500);
});
</script>
</html>
在 React ES6语法中引入socket.io(先执行 npm install socket.io)
import io from 'socket.io-client';
const socket = io.connect('http://localhost:3000');
网友评论