3

I have a server app.js and multiple clients that can connect to my server. I display what the server say to the client in an index.html , but I want to do the same for the server when the client is talking to it, and display what my client says to the server in an HTML page. Right now I'm displaying it with console.log()

Here's my code, I'm using Socket.io : (I'm new to Javascript, this is just a test, so this is really simple )

app.js / Server :

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('clearance', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function (socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
    socket.on('receiveClerance', function (data) {
        console.log(data);
    });
});



app.listen(3000);

Index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();
            var data = "";
            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });

            socket.on('clearance', function (data) {
                addMessage(data.time + data);
                $data = data;
            });

            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
                var btn = document.createElement("BUTTON");
                btn.textContent = "Test";
                btn.onclick = function () {
                    socket.emit('receiveClerance', "La clerance " + $data + " est recu");
                }
                messages.appendChild(btn);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

1 Answer 1

2

Just change your console.log(data) to a socket.emit('message',data).

or make it a function that you can use everywhere, like :

function log(socket,data){
     console.log(data);
     socket.emit('message',data);
}

That way you'll still see the messages on your server console.

Sign up to request clarification or add additional context in comments.

6 Comments

I thought about this silution, but I don't really want to make a special function for a client, I really want to separate my client from my server, and if I do this, I'm just creating a new type of client right ?
no you're not, you're just emitting messages to your client from the server, the same way you do : socket.emit('welcome') on connection. emit is the only way for your server to communicate with the client :) And you already have the handler on the client for the 'message' event, so it's a win-win
And how to display it on a special page ? Because i'm already running something on localhost:3000
the socket connection is bound to the page you open it on, so you can't do that. You could make a single page app, using angular or React and have "fake" urls like localhost:3000/#logs
This seem really complicated with my level :/ I guess there no simple way to do it then :(
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.