提醒一下,这个项目是基于Glitch的以下入门项目构建的,或者是从GitHub克隆的。将Socket.IO添加为依赖项,并在服务器中要求/实例化它,定义为'io',并将http服务器作为参数。 const io = require('socket.io')(http);
需要处理的第一件事是从客户端侦听新连接。 on关键字就是这样 - 监听特定事件。它需要2个参数:一个包含所发出事件标题的字符串,以及一个用于传递数据的函数。在我们的连接侦听器的情况下,我们使用socket来定义第二个参数中的数据。套接字是连接的个人客户端。要在我们的服务器上侦听连接,请在项目中的注释之间添加以下内容: io.on('connection',socket => {
console.log('用户已连接');
});
现在,对于客户端进行连接,您只需要将以下内容添加到client.js中,该客户端经过身份验证后由页面加载: / * global io * /
var socket = io();
注释会抑制您通常会看到的错误,因为文件中未定义“io”。我们已经在chat.pug页面上的Socket.IO库中添加了一个可靠的CDN。现在尝试加载您的应用并进行身份验证,您应该在服务器控制台中看到“用户已连接”! 注意
io()
仅在连接到同一URL /服务器上托管的套接字时起作用。要连接到其他地方托管的外部套接字,您可以使用io.connect('URL');
。当您认为自己已经做对时,请提交您的页面。
## Instructions