socket.io和Express服务器未接收到来自客户端的发射 [英] socket.io and express server not receiving emit from client

查看:72
本文介绍了socket.io和Express服务器未接收到来自客户端的发射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

控制台会记录已建立与套接字的连接",因此它似乎正在连接,但似乎没有触发任何事件,即使在服务器中io.on内部的断开连接"上也是如此.

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"似乎不起作用

"socket.on" doesn't seem to be working

服务器端

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);
    });
});

客户

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;
      });
    });

推荐答案

如果有人遇到相同的问题,我犯了一个简单的错误,尽管如果有人可以确切解释正在发生的事情,那将是很好的.

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.

似乎我没有在客户端上监听连接",因此客户端中什么也没有被调用.最重要的是,我让jquery选择器选择了表单类而不是表单元素.

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.

一旦我添加了socket.on('connect',...) socket.emit即可正常工作,我很快就能够使jquery语句也能正常工作.

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;

确保同时在客户端上打开连接事件(socket.on('connect',...)).

Make sure to turn on the connect event (socket.on('connect',...)) on the client as well.

客户

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;
        });
      })

    });

这篇关于socket.io和Express服务器未接收到来自客户端的发射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆