我正在使用vue-socket-io vuejs2 ,但在开始时遇到问题。我似乎无法与socket-io建立连接。我已按照确切的文档进行操作,但每次调用时都会收到404错误。
build.js?a270:1 GET http://localhost:8080/socket.io/?EIO=3&transport=polling&t=L-T2-Vp 404
这是我在控制台上遇到的错误
@ ./src/main.js 5:0-33 @ multi(webpack)-dev-server / client?http://localhost:8080 webpack / hot / dev-server ./src/main.js
我没有在main.js文件中添加太多代码。这是添加套接字
的主要块import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, 'http://localhost:8080/');
答案 0 :(得分:1)
您必须创建js文件并放入此代码。
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(4113);
io.on('connection', function (socket) {
//console.log('connected');
socket.on('event_name', function (data) {
//console.log(data);
io.emit('event_name', data);
});
});
比起在服务器启动时必须从终端安装express和sockt-io而言,您的错误将得到解决
运行此文件:转到文件所在的路径,然后运行节点file_name
现在,安装vue-socket.io vie npm,然后在main.js文件中创建一个实例,例如:
import VueSocketio from 'vue-socket.io';
Vue.use(VueSocketio, 'http://localhost:4113');
现在,您必须将代码放入。 Vue文件
sockets: {
connect() {
// Fired when the socket connects.
this.isConnected = true;
console.log("server connected");
},
disconnect() {
this.isConnected = false;
console.log("server disconnected");
},
// Fired when the server sends something on the "messageChannel" channel.
messageChannel(data) {
this.socketMessage = data
}
}
现在,通过此方法创建发射服务器方法...
pingServer() {
console.log("click");
this.$socket.emit('pingServer', 'PING!')
},