Home  >  Q&A  >  body text

nginx - How to make the server proactively notify the socket client after receiving http data?

It’s like this. I want to operate a smart light bulb. This is how I currently do it. I operate it on the web page, and then submit the data and save it to the database through http. A client initiates a socket connection and connects to the server. The server fetches data from the database to the client in an endless loop, and sleeps after each operation. If there are many clients, such as 100,000, I have to query the database 100,000 times per second, so I want to improve it. The server receives http After the data is uploaded, it is immediately given to the client, and there is no need to save it in the database.

PHP中文网PHP中文网2714 days ago601

reply all(3)I'll reply

  • 世界只因有你

    世界只因有你2017-05-16 17:08:59

    try yi try “websocket”
    In addition, it is not recommended to operate the database every time you query. You can read it out and put it in the cache, and read it directly from the cache for each query. Then another process monitors the change in the value and updates the cache while modifying the database.

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 17:08:59

    You can consider the in-memory database redis, and then persist it regularly, that is, save it to disk.

    reply
    0
  • 某草草

    某草草2017-05-16 17:08:59

    There are many clients, why do you have to read it 100,000 times? The client and server are permanently connected, and a mapping is stored in the server’s memory:

    map[client_id] = socket_fd
    

    http is submitted and stored in the database, and the server reads the database information in an endless loop. If it is sent to a client, the message should contain the client's client_id. Find the socket_fd from the map and send the message. If it is broadcast to All clients can just traverse the map and send. The number of times the database is read is only related to the number of messages, not the number of clients.

    The database mentioned above can be implemented using message queues such as redis or nsq. The server can open multiple threads or coroutines for concurrent processing. If it is stored in the database, the data can be sent directly. If your service If the terminal crashes, won't the data be lost? Reliability cannot be guaranteed.

    reply
    0
  • Cancelreply