INVALID URL error when trying to create a Websocket in Nodejs

Asked

Viewed 23 times

-1

When I try to create a websocket in nodejs is giving the INVALID URL error and I can not solve.

var config = require('./ext/config.js');     
var ServURL = {
    port: config['port'],
    path: '/slither'
};
const WebS = require('ws');                  

var wss;                                                                        
wss = new WebS({ port: ServURL['port'], path: ServURL['path'] }, function () {          
    console.log('[INFO]: Server started at 127.0.0.1 at port 444');             
});                                                                             

1 answer

0

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

  • [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"); } )

  • How do I do that?

  • 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.