Nuxt Socket.io没有响应,没有任何错误



我正在使用nuxt socket io以及带有socket io的Express.js服务器。当我启动客户端/服务器时,服务器端socket.io连接,服务器的控制台将打印";连接"(。

当我尝试使用nuxt(socket.io的客户端部分(连接时,什么也没发生。Mounted((被正确调用("hm"控制台日志打印出来(,但套接字似乎从未被创建。我试着为CLIENT端测试this.socket.on('connect-error')this.socket.on('connect-timeout')(服务器端socket.io连接正确(,但在等待了大约5分钟后,什么都没有发出。persist: true也不是问题所在;我试图删除它,但遇到了同样的问题。我最初没有this.socket.open(),也有同样的问题,所以我认为这条线也没有任何作用。

NuxtJS前端

mounted() {
console.log("hm");
this.socket = this.$nuxtSocket({
channel: '/profile',
persist: true
})
this.socket.open();
this.socket.on('connection', (socket) => {
console.log("connected")
})
//Listens for the SERVER-EMITTED event 'send'
this.socket.on('send', (message) => {
console.log("client received event!")
console.log(message);
});
},
methods: {
sendMessage() {
// This method IS CALLED correctly with a button (I checked), but the emit is not transmitting
// sends a CLIENT-EMITTED event to the server
this.socket.emit('send-message', {
message: "hey!"
}, (res) => {console.log(res)})
},

nuxt.config.js

io: {
sockets: [{
name: 'main',
default: true,
url: 'http://localhost:3000'
}]
},

我的Express后端(端口为8080(

import express from "express";
import { db } from "./app/config/db.config";
import { authRouter } from "./app/routes/auth.router";
import * as dotenv from "dotenv";
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: '*',
methods: ["GET", "POST"]
}
});
// run on connection to socket
io.on('connection', (socket: any) => {
console.log("connected")
})
// listens for the CLIENT-EMITTED event 'send-message'
io.on('send-message', (message: any) => {
console.log(message + "server received!");
// sends a SERVER-EMITTED event "send" to be received by nuxt client
io.emit('send', "message!")

})
server.listen(process.env.PORT, () => {
console.log(`Server is running on port ${process.env.PORT}`);
});

Axios也在8080端口上运行,我不知道这是否会导致任何问题,但当我尝试运行整个程序(包括登录/注册Axios(时,我没有收到任何错误。有人知道为什么我的事件没有传播吗?非常感谢。

在服务器代码中,您将'send-message'事件侦听器添加到io对象中,该对象是您的主socket.io服务器实例。但是,应该将事件侦听器添加到从connection事件获得的socket对象中。类似于:

// A new connection comes in
io.on('connection', (socket: Socket) => {
// Now we listen for the event that comes from this particular socket
socket.on('send-message', (message: any) => {
// You also use the Socket instance to send events back to clients, not to the `io` Server.
socket.emit('send', "message!");
});
});

Socket实例文档提供了有关如何使用这些套接字的更多信息。

相关内容

最新更新