Lorenzoi
Lorenzoi

Reputation: 31

socket.on doesn't work outside io.sockets.on('connection,..)

I have tried to catch a message from a routing page in this way:

ROUTING PAGE


router.get('/', function(req, res, next){
        var socket= req.app.get('socketio');
        socket.on('Ok', () => console.log("OK"));
        res.render('exercises', {title: 'Exercises', ex: values[0]});
    })

APP.JS

io.sockets.on('connection', function(socket){
    console.log('Connesso');
    app.set('socketio', socket);
})

In order to catch an 'Ok' event from the client in the routing page, but it's doesn't work and I don't figure out why because I've passed socket with app.set

EDIT I emit the event here:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io.connect('http://localhost:8080/');
    </script>
    <div id="addex" hidden>
        <form name="newex" method="get">
            <h1>Inserisci esercizio</h1>
            <p>Nome</p>
            <input id="name" name="name" type="text"></input>
            <p>Descrizione</p>
            <input id="description" name="description" type="text"></input>
            <input type="submit"></input>
        </form>
    </div>
    <button id="add" type="button" onclick=""> Add </button>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <ul>
    <p>Excercises:</p>
     <% ex.forEach(value => { %>
     <li><%= value.name %></li>
    <% }); %>

    </ul>
    <script type="text/javascript">
        add.onclick = function(event){
            addex.hidden = false;
        }
        newex.onsubmit = function(event){
            event.preventDefault();
            socket.emit('message', {name: document.getElementById('name').value, desc: document.getElementById('description').value});

        }
    </script>
  </body>
</html>

Upvotes: 0

Views: 445

Answers (2)

The Bumpaster
The Bumpaster

Reputation: 964

Try to follow this example:

const socketServer = SocketService.io = socketIo(server, {
    path: process.env.WEBSOCKETS_PATH || "/socket.io",
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin ? req.headers.origin : "*", // or the specific origin you want to give access to,
            "Access-Control-Allow-Credentials": true,
        };
        res.writeHead(200, headers);
        res.end();
    },
});

export let socketConnection;

socketServer.on("connect", async (connection) => {
    logger.log("Successfully established socket connection.");
    connection.emit("connection", { code: 200, message: "Socket connection established." });
    socketConnection = connection;
    connection.on("my event", async (streamConnection) => {
        logger.log("Successfully established socket my event.");
        connection.emit("connection", { code: 200, message: "My event established, listening on 'my event' event." });
    });
});

Now in some other part of code you can import 'socketConnection', and use it.

Upvotes: 1

ShocKwav3_
ShocKwav3_

Reputation: 1760

.emit is to fire an event and .on listens for event.

With that being so, In your router code by doing socket.on('Ok', () => console.log("OK")); you are trying to listen to an event named Ok.

Now to listen to that event, there has to be an event fired named Ok. In your client by doing this socket.emit('message', ...) you are firing an event named message.

In your given code I don't see if you need this message or not but summary is to listen to and event named Ok you have to socket.emit('Ok', ...) somewhere else; your client in this case.

This is the bare basic of socket.io. I suggest you check the documentations and some tutorials because it was confusing for me in the beginning as well :)

Hope that helps you!

Cheers!

Upvotes: 0

Related Questions