public
Created

simple node.js socket.io client/server example

  • Download Gist
chat.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
<html>
<head>
<title>Node.js IL Chat</title>
<script type="text/javascript" src="/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script language="javascript">
var socket;
$(document).ready(function()
{
socket = io.connect('/');
socket.on('message', function (data) {
var content = $('#messages').html() + data + '<br/>';
$('#messages').html(content);
});
$('#message').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
postMessage();
}
 
});
 
});
function postMessage()
{
if (socket) {
socket.emit('message', $('#message').val());
$('#message').val('');
}
}
 
</script>
<style>
body {
background-color:#000000;
color: green;
}
</style>
</head>
<body>
<h2 class="white">Post your messages</h3>
<table>
<tr><td class="white">Your Message:</td><td><input id="message" type="text" size="50"></td></tr>
</table>
<h2 class="white">Messages</h3>
<div id="messages">
</div>
</body>
</html>
chat.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
var Express = require('express'),
app = Express.createServer(),
io = require('socket.io').listen(app);
 
io.configure('production', function(){
io.enable('browser client etag');
io.set('log level', 1);
 
io.set('transports', [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling',
]);
});
 
io.configure('development', function(){
io.set('transports', ['websocket']);
});
 
app.get('/', function (req, res) {
res.redirect('/chat.html');
});
 
app.use(Express.static(__dirname + '/static'));
app.listen(process.env.PORT || process.argv[3] || 8080);
 
io.sockets.on('connection', function(client){
var userName;
console.log("user connected!");
client.emit('message', 'please insert user name');
client.on('message', function(message){
if (!userName) {
userName = message;
console.log(userName + ' is connected :)');
client.emit('message', 'Welcome ' + userName);
client.broadcast.emit('message', userName + ' is connected');
}
else {
client.emit('message', 'me: ' + message);
client.broadcast.emit('message', userName + ' says: ' + message);
}
});
 
client.on('disconnect', function() {
if (userName) {
console.log(userName + " left");
client.broadcast.emit('message', userName + ' left us :(');
}
else {
console.log("anonymous left");
}
});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.