简体   繁体   English

Socket.io在连接事件上的调用确认

[英]Socket.io call ack on connect event

Is there any way too utilize the ack argument on the connect event in Node.js? 有没有办法在Node.js的connect事件上利用ack参数? Something like this: 像这样:

//client.js
socket.on('connect', (data) => {
  console.log(data); // I want to print 'lol' here
});

//server.js
io.on('connect', (socket, ack) => {
  ack('lol'); // TypeError: ack is not a function
});

Reference for ack: https://socket.io/docs/server-api/#socket-emit-eventname-args-ack ack的参考: https : //socket.io/docs/server-api/#socket-emit-eventname-args-ack

There is no specific ack data that you can send for the connect event. 没有可为连接事件发送的特定确认数据。 You can just .emit() a message to the client when the server receives the connect. 当服务器接收到连接时,您可以仅.emit()向客户端发送一条消息。

//client.js
socket.on('connect', () => {
  console.log('client connected');
});

socket.on('welcome', function(data) {
  console.log(data); // 'lol'
});

//server.js
io.on('connect', (socket) => {
  // send welcome message upon connect
  socket.emit('welcome', 'lol');
});

It doesn't look like the socket.connect() or socket.open() methods take an ack argument. 它看起来不像socket.connect()或socket.open()方法带有ack参数。 I generally will emit a 'connected' event from the server once a connection from the client is established. 一旦与客户端建立连接,我通常会从服务器发出“已连接”事件。 You can receive this emission and add your behavior as needed. 您可以接收此发射,并根据需要添加您的行为。

server.js server.js

io.on('connect', function(socket) {
  socket.emit('connected');
});

client.js client.js

socket.on('connected', function() {
  console.log('Connected');
});

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

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