Javascript Socket.io:从客户端发出不起作用
我试图在客户机上发出一个事件,但服务器根本没有响应。控制台中未出现消息('Received!'),以下事件未启动。单击按钮时必须发出事件。其他操作(如向控制台输出消息)工作正常,但事件不会启动。有什么问题?С连接事件正常工作 服务器:Javascript Socket.io:从客户端发出不起作用,javascript,express,websocket,socket.io,Javascript,Express,Websocket,Socket.io,我试图在客户机上发出一个事件,但服务器根本没有响应。控制台中未出现消息('Received!'),以下事件未启动。单击按钮时必须发出事件。其他操作(如向控制台输出消息)工作正常,但事件不会启动。有什么问题?С连接事件正常工作 服务器: class ChatHandlers { constructor() { this.names = {}; this.connection = this.connection.bind(this); thi
class ChatHandlers {
constructor() {
this.names = {};
this.connection = this.connection.bind(this);
this.send = this.send.bind(this);
this.message = this.message.bind(this);
}
connection(socket) {
socket.emit('new_user', {
name: 'Example name'
});
}
send(socket) {
console.log('Received!');
var ip = socket.handshake.address;
io.sockets.emit('message', {
name: ip,
message: socket.message
});
}
message(socket) {
console.log('Success!');
}
}
var handlers = new ChatHandlers();
io.on('connection', handlers.connection);
io.on('send', handlers.send);
客户:
var socket = io.connect('http://localhost:8080/');
socket.on('connect', function (data) {
socket.on('new_user', function (data) {
console.log(data.name);
});
socket.on('message', function (data) {
console.log(data);
});
$('#send').click(function() {
socket.emit('send', {
message: $('#mess').val()
});
$('#mess').val('');
});
尝试将最后一行服务器
io.on('send',handlers.send)
toconnection(socketd)
socket.emit('new_user'…无需将消息处理程序放在socket中。on('connect',…)
io.on('send',handlers.send);
在服务器端是错误的。您需要侦听特定的连接套接字,而不是io
。