📜  socket io 查询 - Javascript (1)

📅  最后修改于: 2023-12-03 14:47:30.408000             🧑  作者: Mango

Socket.IO Query

Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server. One of the features of Socket.IO is the ability to send and receive data with query parameters. Query parameters are key-value pairs that are added to the end of a URL, separated by a question mark. For example:

http://example.com/?name=John&age=30

In Socket.IO, query parameters can be added to a connection URL to send data between the client and server.

How to Use Query Parameters

To add query parameters to a Socket.IO connection, simply pass an object as the second argument to the connect() method on the client:

const socket = io.connect('http://example.com', {
  query: {
    name: 'John',
    age: 30
  }
});

On the server, the query parameters can be accessed in the connection event:

const io = require('socket.io')();

io.on('connection', (socket) => {
  console.log(socket.handshake.query); // { name: 'John', age: '30' }
});

Query parameters can also be added to specific Socket.IO events by calling the emit() method with an object as the second argument:

socket.emit('event', {
  name: 'John',
  age: 30
});

On the server, the data can be accessed in the event handler:

socket.on('event', (data) => {
  console.log(data); // { name: 'John', age: 30 }
});
Conclusion

Socket.IO query parameters provide a simple and flexible way to send and receive data between the client and server. By using query parameters, developers can easily customize their Socket.IO connections and events to suit their needs.