问题
The console logs "connection to socket made," so it seems to be connecting, but no events seem to be triggered, even on 'disconnect' inside io.on in the server.
"socket.on" doesn't seem to be working
SERVER SIDE
var server = app.listen(app.get('port'), () => {
console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
console.log(' Press CTRL-C to stop\n');
});
var io = socket(server);
io.on('connection', function(socket){
console.log('connection to socket made');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
CLIENT
ul.pages
li.chat.page
div.chatArea
ul.messages
input.inputMessage(placeholder='Type here...')
li.login.page
.form
h3.title What's your nickname?
input.usernameInput(type="text", maxlength="14")
script(src="/socket.io/socket.io.js")
script(src="https://code.jquery.com/jquery-1.11.1.js")
script.
$(function () {
var socket = io('http://localhost:8080/chat', {transports: ['websocket']});
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
回答1:
If anyone has the same problem, I made a simple mistake, though if anyone can explain exactly what's going on, that would be great.
It seems that I wasn't listening on the client for 'connect', so nothing was being called in the client. on top of that I had the jquery selector selecting class of form not a form element.
As soon as I added the socket.on('connect',...)
socket.emit was working and I was quickly able to get the jquery statement to work out too.
tldr;
Make sure to turn on the connect event (socket.on('connect',...)
) on the client as well.
CLIENT
script.
$(function () {
var socket = io('http://localhost:8080', {transports: ['websocket']});
socket.on('connect', function(){
console.log("connected on client!");
socket.emit('chat message', "hello there");
$('form').submit(function(){
console.log("form submitted");
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
})
});
来源:https://stackoverflow.com/questions/49093416/socket-io-and-express-server-not-receiving-emit-from-client