Answer the question
In order to leave comments, you need to log in
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);
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
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>
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');
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question