最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

未使用vuejs从socket.io服务器获取消息

网站源码admin43浏览0评论

未使用vuejs从socket.io服务器获取消息

未使用vuejs从socket.io服务器获取消息

我一直在努力允许vuejs应用程序与远程独立的socket.io服务器对话。我已经设法让vuejs应用程序将消息发送到socket.io服务器(通过nodejs实例上的控制台日志确认),但是我似乎无法让它监听响应。

我正在以最基本的形式使用Vue-socket.io,并且我已将localhost和null添加到起源以希望排除该问题。

  • 我正在localhost:3000上运行socket.io服务器
  • 我正在运行vuejs应用在localhost:8888]

为什么我无法从以下代码中得到答复?顺便说一句,我也没有在app.vue中获得关于sockets.connect和sockets.customMessage的任何控制台日志。

socket.io(nodejs)服务器:

var http = require('http').createServer({
    origins: ['localhost','null',null]
});
var io = require('socket.io')(http);

io.on('connection', (socket) => {
    console.log('a user connected');
    socket.broadcast.emit('hi, welcome to live chat');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });
    socket.on('chatMessage', (msg) => {
        console.log('chatMessage: ' + msg);
        io.emit('chatMessage', msg);
    });
})



http.listen(3000, () => {
    console.log('listening on port 3000');
});

app.js(vuejs应用的入口):

import Vue from 'vue'
//import store from './store'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from "socket.io-client"

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://localhost:3000'
}))

new Vue({
    render: h => h(App)
}).$mount('#app')

App.vue:

<template>
    <div>
        hello chat app
        <input type="text" v-model="message"/>
        <button @click="clickButton()">Send Msg</button>
    </div>
</template>

<script>
    export default {
        name: "Home",
        sockets: {
            connect: function () {
                console.log('socket connected')
            },
            chatMessage: function(data) {
                console.log('this method was fired by the socket server. eg: io.emit("chatMessage", data)')

            }
        },
        methods: {
            clickButton: function () {
                console.log('button clicked');
                console.log(this.message);
                // $socket is socket.io-client instance
                this.$socket.emit('chatMessage', this.message)
            }
        },
        data: () => {
            return {
                message: '',
            };
        },
        computed: {

        },
        mounted() {
            this.$socket.on('chatMessage',data => {
                console.log('listen fired')
                console.log(data);

            });
        }
    }
</script>
回答如下:

您能否尝试将此配置放入app.js

只需添加一个连接选项,并在实例化VueSocketIO实例时使用它。

const options = { path: '/socket.io/' }; //<--

Vue.use(new VueSocketIO({
    debug: true,
    connection: 'http://localhost:3000',
    options //<--
  })
);

然后重试?如果它不起作用,我可以发布我的解决方案。

发布评论

评论列表(0)

  1. 暂无评论