【问题标题】:connection between client-side and server-side not working on socket.io客户端和服务器端之间的连接在 socket.io 上不起作用
【发布时间】:2017-12-31 21:29:17
【问题描述】:

客户端和服务器端之间的套接字连接有问题。

我在服务器端有这段代码:-

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('disconnect', function(){
    console.log('user disconnected');
  });
});

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

以及客户端上的这段代码:-

<html>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
    <script>
        var socket = io();
    </script>
</body>
</html>

服务器端的代码正在运行,但在客户端我有这些错误:-

谁能帮我解决问题? 非常感谢:(

【问题讨论】:

  • 浏览器控制台有错误吗?
  • 没有。浏览器控制台没有错误
  • 不幸的是..同样的问题
  • 服务器端呢?你能从控制台显示服务器消息吗?
  • 仅在执行服务器端文件时显示此消息:- 监听 *:3000

标签: node.js express socket.io


【解决方案1】:

看起来您正在将文件直接打开到浏览器中。实际上,您没有指定提供 html 的路径。这样socketio就可以POST并在那里轮询数据。

app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });

如果您确实需要直接在浏览器中打开文件而不是通过 nodejs 在同一端口上提供服务,则必须在客户端套接字中指定主机和端口。

而不是简单地使用io(),它会寻找你可以使用的本地端口

var socket = io("http://localhost:3000");

【讨论】:

  • 同样的问题。
  • @alial-shelleh 我已经尝试过你的代码,它对我来说工作正常。尝试客户端编辑的解决方案。
  • 您是否添加了路由或尝试修改客户端代码。你能显示你要打开哪个网址吗?
【解决方案2】:

所以这对我来说是如何工作的

// server

const app = require('express')();
const http = require('http').createServer(app);
//                           ^^^^^^^^^^^^
const io = require('socket.io')(http);

// here you should serve your index.html file
// and the socket io will know which socket to track
app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

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

// client/index.html
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      // here it automatically track localhost:3000
      var socket = io();
    </script>

  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多