用socket.oi实现酒店订单提醒
时间: 2023-08-15 21:11:23 浏览: 185
要实现酒店订单提醒,可以使用 Socket.IO 技术,以下是示例代码:
1. 首先,安装 Socket.IO:
```
npm install socket.io --save
```
2. 在服务器端,创建 Socket.IO 实例:
```
const io = require('socket.io')(server);
```
3. 在客户端,连接 Socket.IO 服务器:
```
const socket = io.connect('http://localhost:3000');
```
4. 当订单被创建时,服务器发送订单信息到客户端:
```
io.on('connection', (socket) => {
console.log('A user connected');
// Send order notification
socket.emit('newOrder', { order: 'New order created!' });
});
```
5. 客户端监听服务器发送的订单信息:
```
socket.on('newOrder', (data) => {
console.log(data.order);
// Show notification to user
});
```
6. 客户端收到订单信息后,可以通过浏览器提供的 Notification API 显示通知:
```
if (Notification.permission === 'granted') {
// Send notification
new Notification('New Order', {
body: data.order,
icon: 'path/to/icon.png',
});
}
```
完整示例代码如下:
服务器端:
```
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server);
// Serve static files
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('A user connected');
// Send order notification
socket.emit('newOrder', { order: 'New order created!' });
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
```
客户端:
```
<!DOCTYPE html>
<html>
<head>
<title>Hotel Order Notification</title>
</head>
<body>
<h1>Hotel Order Notification</h1>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io.connect('http://localhost:3000');
socket.on('newOrder', (data) => {
console.log(data.order);
if (Notification.permission === 'granted') {
new Notification('New Order', {
body: data.order,
icon: 'path/to/icon.png',
});
}
});
</script>
</body>
</html>
```
注意:浏览器要支持 Notification API,否则无法显示通知。
阅读全文