[英]Socket.on() does not execute
I am trying to make a chat app with socket.io and I've run into a weird occurrence: my server receives the messages that I sent but the client doesn't. 我正在尝试使用socket.io创建一个聊天应用程序,但是我遇到了一个奇怪的情况:我的服务器收到了我发送的消息,但客户端却没有。
Server Code: 服务器代码:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '\\index.html');
});
io.on('connection',function(socket){
socket.on('chat message', function(msg){
io.emit(msg)
console.log('message: ' + msg)
})
})
http.listen(3002,function(){
console.log('listening on 3002');
});
And here is the client's code: 这是客户的代码:
<script>
$(function () {
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
console.log(msg)
// $('#messages').append($('<li>').text(msg));
});
});
</script>
where #m is am input field with the message I want to send #m是我要发送的消息的输入字段
You have to emit an event name with some data : 您必须发出带有一些数据的事件名称:
socket.emit(eventName[, …args][, ack])
socket.emit(eventName [,…args] [,ack])
on the Server : 在服务器上:
io.on('connection',function(socket){
socket.on('chat message', function(msg){
io.emit('newMessage', msg )
// ^^^^^^^^^^ ^^^^
// event name data
console.log('message: ' + msg)
})
})
on the client : 在客户端上:
socket.on('newMessage', function(msg){
console.log(msg)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.