S
S
Sienore2017-08-06 12:03:25
CRM
Sienore, 2017-08-06 12:03:25

How to transfer data from HTTP server to WebSocket?

Good afternoon.
It is necessary to implement a pop-up contact card in your own CRM system. Telephony sends POST requests to my server where I parse them. How to transfer data from HTTP server to WebSocket?
HTTP server code

http.createServer(function (req, res) {
if (req.method == 'POST') {
    req.on('data', function(chunk) {
      console.log("Received body data:");
      console.log(chunk.toString());
    });
   
    req.on('end', function() {
      // empty 200 OK response for now
      res.writeHead(200, "OK", {'Content-Type': 'text/html'});
      res.end();
    });    
  }
}).listen(1337);

WebSocket Server Code
const WebSocket = require('ws');
 
const wss = new WebSocket.Server({ port: 1337});
 
wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });
 
  ws.send('something');
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Coder321, 2017-08-06
@Coder321

Events https://nodejs.org/api/events.html

V
Voskan Voskanyan, 2017-08-07
@HackerX

I advise you to use the Socket.io library instead of the usual ws module, and regarding the transfer of data from HTTP to ws, this is done like this:
Customer:

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <title>Socket.io</title>
  <script src="/socket.io/socket.io.js"></script>
</head>
<body>
  <script>
    var socket = io();
    socket.on("hello", function(serverData) {
       alert(serverData);
    });
  </script>
</body>
</html>

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

const mySuperData = "hellooooo kuku";

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
  socket.emit("hello", mySuperData);
});
http.listen(3000, () => {
  console.log('Сервер слушает порт 3000');
});

Example using Node.js / Socket.io .
Node.js - event handling .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question