Skip to content

Instantly share code, notes, and snippets.

@marcusmoore
Created June 11, 2015 20:24
Show Gist options
  • Save marcusmoore/0978023a9bfa5714ff8b to your computer and use it in GitHub Desktop.
Save marcusmoore/0978023a9bfa5714ff8b to your computer and use it in GitHub Desktop.
Socket.IO chat example

Walkthrough for chat app from Socket.io's getting started guide here

<!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">
<form action="">
<input type="text" id="m" autocomplete="off"><button>Send</button>
</form>
</ul>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
// Push new messages
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>
// Initialize app as function handler to be supplied to HTTP server
var app = require('express')();
var http = require('http').Server(app);
// Initalize new socket.io instance with http object
var io = require('socket.io')(http);
// Define route handler for /
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
// Log user connected
console.log('user connected');
// Log user disconnected
socket.on('disconnect', function(){
console.log('user disconnected');
});
// Catch new message and push it out to everyone
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
// Listen on port 3000
http.listen(3000, function(){
console.log('listening on *:3000');
});
{
"name": "socket-example",
"version": "0.0.1",
"description": "tryin out socket.io",
"dependencies": {
"express": "^4.10.2",
"socket.io": "^1.3.5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment