简体   繁体   中英

How to listen to an event after emitting an event Socket.io

I want to build an SQL handler server side on my nodejs server.

I would like my nodejs to recieve requests from client side - for example:

client.js

socket.emit("sql-query", "SELECT * FROM *");
socket.on('sql-response', results => {
    do things with results...
}

server.js

socket.on('sql-query', query => {
    connection.query(query, function(error, results, fields)) {
        if(results > 0) socket.emit('sql-response', results);
        else console.log('No results... yet !');
    }
});

Problem is, if I do that, every function that needs to make an SQL request will get the sql-response event.

I would want my emit to return results without having to catch another event (that every file using SQL request will catch).

Something like this: server.js

socket.on('sql-query', query => {
    connection.query(query, function(error, results, fields)) {
        if(results > 0) socket.return(results); //I know this is wrong and that's not how events work.
    }
});

General idea: Make SQL requests using a nodejs / socket.io server from other files.

Please tell me if it's a headache to do that and if there is another better way of achieving this.

Thank you

I am not pretty sure If I got you, but for me, it works as you want, but it is the same code that you are using, because socket.emit does not multicast

Server

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

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

io.on('connection', (socket) => {
  socket.on('sql-query', (query) => {
    socket.emit('sql-response', `this is your response: ${query}`);
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

Client

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script>
    var socket = io();
    var form = document.getElementById('form');
    var input = document.getElementById('input');

    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        console.log(input.value)
        socket.emit('sql-query', input.value);
        input.value = '';
      }
    });

    socket.on('sql-response', function(msg) {
      var item = document.createElement('li');
      item.textContent = msg;
      messages.appendChild(item);
      window.scrollTo(0, document.body.scrollHeight);
    });
  </script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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