Skip to content

Instantly share code, notes, and snippets.

@rpragana
Last active June 17, 2017 12:57
Show Gist options
  • Save rpragana/d24f330258c2a619752fe035b29f422d to your computer and use it in GitHub Desktop.
Save rpragana/d24f330258c2a619752fe035b29f422d to your computer and use it in GitHub Desktop.
Web Sockets
<!DOCTYPE html>
<html>
<head>
<title>WebSockets</title>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="zepto.min.js"></script>
</head>
<body>
<form>
<div id="nome-div">
<input id="nome" name="nome" autocomplete="off"
autofocus placeholder="Entre com seu nome ou apelido" />
<button>Entra</button>
</div>
<div id="bem-vindo"></div>
<ul id="mensagens"></ul>
<div id="input-div">
<input id="mensagem" name="mensagem"
autocomplete="off"
placeholder="entre aqui sua mensagem"></input>
<button>Envia</button>
</div>
</form>
<script>
websocket = new WebSocket("ws://localhost:9000/");
$('form').submit(function() {
var nome = $('#nome').val() ? $('#nome').val() : 'Anônimo';
$('#nome-div').hide();
$('#bem-vindo').text('Olá ' + nome);
websocket.send(JSON.stringify({
nome: nome,
mensagem: $('#mensagem').val()
}));
$('#mensagem').focus();
$('#mensagem').val('');
return false;
});
websocket.onmessage = function(evt) {
$('#mensagens').append($('<li>').html(evt.data));
};
websocket.onerror = function(evt) {
$('#mensagens').append($('<li>')
.text('<span style="color: red;">ERROR:</span>'
+evt.data));
};
</script>
</body>
</html>
#!/usr/bin/env nodemon
var fs = require('fs');
var path = require('path');
var express = require('express');
var ws = require('ws');
var app = express()
app.use(express.static(__dirname + '/'));
app.listen(8000);
console.log('Aponte seu navegador para https://localhost:8000/');
var repl = require('repl');
var rinst = repl.start('> ');
rinst.context.app = app
var wsock = new ws.Server({
port: 9000
});
wsock.broadcast = function broadcast(data) {
wsock.clients.forEach(function each(client) {
client.send(data);
});
};
wsock.on('connection', function(wsk) {
wsk.on('message', function(msg) {
data = JSON.parse(msg);
if (data.mensagem) wsock.broadcast('<strong>' + data.nome +
'</strong>: ' + data.mensagem);
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font: 13px Helvetica, Arial;
}
form input {
border: 0;
padding: 10px;
width: 90%;
margin-right: .5%;
}
form button {
width: 9%;
background: rgb(130, 224, 255);
border: none;
padding: 10px;
}
#nome-div, #bem-vindo {
background: #AAA;
padding: 10px;
width: 100%;
}
#input-div {
background: #000;
padding: 3px;
position: fixed;
bottom: 0;
width: 100%;
}
#mensagens {
list-style-type: none;
margin: 0;
padding: 0;
}
#mensagens li {
padding: 5px 10px;
}
#mensagens li:nth-child(odd) {
background: #eee;
}

Web Sockets - arquivos

  • server.js
  • index.html
  • style.css
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment