[英]socket.on not working in client side
I'm studying nodejs + vuejs + socket.io Testing sending message and reciving on server side and client side. 我正在研究nodejs + vuejs + socket.io测试发送消息并在服务器端和客户端进行接收。
On server side is working, I'm recieving the console(message: text) But, the console.log
on the client side is not working. 在服务器端,我正在接收控制台(消息:文本)但是,客户端上的
console.log
无法正常工作。 Nothing appears. 什么也没出现。
index.html: index.html:
<script src="/socket.io/socket.io.js"></script>
<body>
<div class="container" id="todo">
<h1><%= title %></h1>
<h3>{{subtitle}}</h3>
<p>Welcome to <%= title %></p>
<div id="app-5">
<p>{{ subtitle }}</p>
<button v-on:click="sendMessage">Send Message</button>
</div>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="/javascripts/app.js"></script>
app.js: app.js:
var socket = io();
var vm = new Vue({
el: '#todo',
data: {
subtitle: 'Hello Vue.js!',
text: 'Hello Friends',
menssages: []
},
methods: {
sendMessage: function () {
socket.emit('chat message', this.text);
}
}
});
socket.on('chat message', function(msg){
console.log('Client side message: ' + msg)
});
nodejs server: nodejs服务器:
io.on( "connection", function( socket ) {
console.log( "A user connected" );
socket.on('chat message', function(msg){
console.log('messagem: ' + msg);
});
});
I'm recieving the message on terminal server. 我在终端服务器上收到消息。 But not recieving the
console.log('Client side message: ' + msg)
on the browser. 但在浏览器上未收到
console.log('Client side message: ' + msg)
。
This is mainly a socket.io question. 这主要是一个socket.io问题。 You are emitting an event from the client:
您正在从客户端发出事件:
socket.emit('chat message', this.text);
and then listening on that event on the server: 然后在服务器上监听该事件:
socket.on('chat message', function(msg){
console.log('messagem: ' + msg);
});
which makes sense and, as you say yourself, works fine: the message gets logged on the server. 这很有意义,而且就像您自己说的那样,效果很好:消息已记录在服务器上。
However, listening on the chat message
event on the client: 但是,在客户端上监听
chat message
事件:
socket.on('chat message', function(msg){
console.log('Client side message: ' + msg)
});
does not work until the server has emitted this event. 在服务器发出此事件之前,它不起作用。
In other words, try executing: 换句话说,尝试执行:
socket.emit('chat message', 'Hello World.');
on the server to see Hello World
logged on the client. 在服务器上查看
Hello World
登录到客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.