简体   繁体   English

socket.io客户端无法向服务器发送消息

[英]socket.io client unable to emit message to server

I can't figure out why my socket.io server isn't receiving messages from the client. 我不知道为什么我的socket.io服务器没有收到来自客户端的消息。 Here is my server JS file: 这是我的服务器JS文件:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){

    console.log('a user connected');

    socket.on('bid', function(msg){
        console.log('received:' + msg);
    });

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });
});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

And here is the client-side code: 这是客户端代码:

$(function () {

    var socket = io(':3000/socket.io/socket.io.js');

    $('#bid-form').on('submit',function(){
        socket.emit('bid', 'test');
        console.log('emit');
        return false;
    });
});

When I open and close the browser page I see the "user connected" and "user disconnected" messages on the server console so I know it's making the connection. 当我打开和关闭浏览器页面时,在服务器控制台上看到“用户已连接”和“用户已断开”消息,因此我知道它正在建立连接。

When I submit the form I see the "emit" message in the browser console so I know the form submit event is firing but I'm not receiving the test message on the server. 当我提交表单时,我在浏览器控制台中看到“发出”消息,因此我知道表单提交事件正在触发,但是我没有在服务器上收到测试消息。 Nothing seems to happen on the client or sever end, it seems like the "socket.emit" function isn't doing anything. 在客户端或服务器端似乎什么也没有发生,看来“ socket.emit”功能没有做任何事情。

What am I doing wrong? 我究竟做错了什么?

My assumption is that you are running your express server on localhost . 我的假设是您正在localhost上运行Express服务器。

It looks like you're accessing your HTML file directly through file:// unless your client-sided code is hosted by a different web server. 看起来您正在直接通过file://访问HTML文件,除非您的客户端代码由其他Web服务器托管。 But regardless of that, here's how you can connect: 但是无论如何,这是连接方式:

<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io("http://localhost:3000");
    $('#bid-form').on('submit',function(){
      socket.emit('bid', 'test');
      console.log('emit');
      return false;
    });
  });
</script>

You will need to load the socket.io.js file through the script tag. 您将需要通过script标签加载socket.io.js文件。 Then connect to your socket.io server by providing the host of the socket.io server to the io() function. 然后通过为io()函数提供socket.io服务器的主机,连接到socket.io服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM