Chat: un ejemplo

Necesitamos instalar express y socket:

npm i express

npm i socket.io

 

server.js


var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
io.emit('chat message', msg);
});
});

http.listen(1337, function () {
console.log('escuchando en *:1337');
});

index.html


<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font: 13px Helvetica, Arial;
}

form {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}

form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}

form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}

#messages {
list-style-type: none;
margin: 0;
padding: 0;
}

#messages li {
padding: 5px 10px;
}

#messages li:nth-child(odd) {
background: #eee;
}
</style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function (e) {
e.preventDefault(); // prevents page reloading
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function (msg) {
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>

Añadimos log. En server.js:

var fs = require('fs');

fs.open('log.txt', 'w', function (err, file) {
    if (err) throw err;
    console.log('Creado!');
});
app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

Después del emit:

  fs.appendFile('log.txt', msg+"\r\n", function (err) {
            if (err) throw err;
            console.log('Guardado!');
        });

Publicado por

Avatar del usuario

Juan Pablo Fuentes

Formador de programación y bases de datos