Have you tried using the socket.io library with express? I found it very simple, there is a lot of information in the documentation which facilitates the integration:
socket documentation.io
The example socket server: socket.js, then Node socket.js is in the air.
const port = process.env.PORT || 21001; //porta padrão
var app = require('express')();
var http = require('http').createServer(app);
const socketio = require('socket.io');
var io = socketio(http, {perMessageDeflate: false});
http.listen(port, () => {
console.info(`Servidor socket inicializado usando express na porta ${port}`);
});
io.set('transports', ['websocket']);
io.on("connection", (socket) => {
console.info(`Client entrou [id=${socket.id}]`);
socket.on("disconnect", () => {
console.info(`Client saiu [id=${socket.id}]`);
});
socket.on("mensagem-enviada", dados => {
socket.broadcast.emit('mensagem-repassada', dados);
console.log(`Localização recebida e repassada: ${JSON.stringify(dados)}`)
});
});
On the client side, you can use it like this:
<script type="text/javascript">
var socket = io('http://localhost:21001', {transports: ['websocket']});
socket.on('connect', () => {
console.log("socket conseguiu conecta");
});
socket.on('mensagem-repassada', data => {
console.log("localização recebida que foi repassada:");
console.log(data);
});
function enviarMensagem(dados){
socket.emit("mensagem-enviada", dados);
}
</script>
It seems to be a really good option, but my project is a mod and I can not change library, if I could I would probably use socket.io
– Rafarl Guimaraes
[Link] https://github.com/websockets/ws/blob/master/doc.ws.md#new-websocketserveroptions-callback You should instantiate the new Websocket.Server({options...}, () => { console.log("your callback"); } )
– Thomaz Diogo
How do I do that?
– Rafarl Guimaraes
Rafael, try to understand little more the documentation of the websockets, there is the client side and server side. I couldn’t understand it enough to explain it. You have to upload the websockets service (server) and another part is the client that will communicate with a websocket server.
– Thomaz Diogo