onedesign/express-socketio-tutorial

'socketToMe' 이벤트가 작동하지 않습니다.

Opened this issue · 2 comments

nccho commented

I raised the socketToMe event on the server router, but I did not receive it from the client.
The server was working properly after raising the connection event and adding the following code inside it:
Is it correct to work without the connection event?

[router code]

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.io.on('connection', function(socket) {
        // 클라이언트로 news 이벤트를 보낸다.
        socket.emit('server-news', {
            hello: 'world'
        });

        // 클라이언트에서 my other event가 발생하면 데이터를 받는다.
        socket.on('client-news', function(data) {
            console.log(data);
        });
    });
    res.render('users', {
        title: 'Express'
    });
    //res.send('respond with a resource.');
});

module.exports = router;

[client code]

<script src="../socket.io-client/dist/socket.io.js"></script>  
<script>  
// localhost로 연결한다.
var socket = io.connect('http://localhost:3000');
socket.on('server-news', function(data) {
    console.log(data);
    //서버에 my other event 이벤트를 보낸다.
    socket.emit('client-news', {
        my: 'data'
    });
});
</script>  

Hey @nccho!

I updated the format of your question a bit to make the code a bit nicer, but I'm not sure I'm totally understanding your issue.

Is the [router code] what you're placing in routes/users.js? Just trying to create a reduced test case for this.

nccho commented

Hi! @brianjhanson
I am studying English. so it is difficult to explain.
I am using a Google Translator.

I have not worked with the sample code below.
image

but, But this worked because I did this.
router.get('/', function (req, res, next) { res.io.on('connection', function (socket) { socket.emit('socketToMe', 'users'); res.send('respond with a resource.'); }); });

I hope it has been well explained to you.
thank you.