我正在尝试使用socket.io从我的Express服务器接收事件到python客户端,但是什么也没发生。
这是我的python客户端:
import socketio
sio = socketio.Client()
sio.connect("http://localhost:5000/")
print('my sid is', sio.sid)
@sio.event
def message(data):
print('I received a message!')
@sio.on('my message')
def on_message(data):
print('I received a message!')
这是我的服务器:
const express = require('express');
const connectDB = require('./config/db');
const chat = require('./routes/api/ChatAPI');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
//connect Database
connectDB();
app.use(express.json({ extended: false }));
app.get('/', (req, res) => res.send('API RUNNING'));
app.use('/api/chat', chat);
const PORT = process.env.PORT || 5000;
server.listen(PORT, function(){
console.log('listening on port ' + PORT);
io.on('connection', function (socket) {
console.log("USER CONNECTED...");
});
});
我在/ api / chat上有一条路由,当我发布聊天项目时,我会向服务器发送一个emmit,如下所示:
router.post('/', async (req, res) => {
console.log(req.body);
const chat1 = await Chat.findOne({
otherID: req.body.otherID,
ID: req.body.ID
});
const chat2 = await Chat.findOne({
otherID: req.body.ID,
ID: req.body.otherID
});
if (chat1) {
chat1.chat = [...chat1.chat,req.body.chat];
chat1.save();
} else if (chat2) {
chat2.chat = [...chat2.chat,req.body.chat];
chat2.save();
} else {
const newChat = new Chat({
ID: req.body.ID,
otherID: req.body.otherID,
chat: req.body.chat
});
newChat
.save()
.then(post => res.json(post))
.catch(err => console.log(err));
}
io.emit('message', req.body);
res.status(200).json({post:"success"});
});
但是我的python客户端未检测到io.emit消息,我在请求中获得了响应,但在套接字上却没有得到响应,有人知道我的代码有什么问题吗?