Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created December 10, 2011 21:53
Show Gist options
  • Save johnhunter/1456613 to your computer and use it in GitHub Desktop.
Save johnhunter/1456613 to your computer and use it in GitHub Desktop.
Nodejs chat with socket.io
/*
Websockets using http://socket.io/
Also with express web mvc framework http://expressjs.com/
*/
var app = require('express').createServer(),
io = require('socket.io').listen(app),
port = 88;
app.listen(port);
// http routing:
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// socket events
io.sockets.on('connection', function (socket) {
socket.emit('toClient', {
type: 'status',
msg: 'Connection established'
});
socket.on('toServer', function (data) {
// do any required processing with incoming data
// send data to others
data.type = 'broadcast';
socket.broadcast.emit('toClient', data);
// sned copy to self
data.type = 'cc';
socket.emit('toClient', data);
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Socket chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 10px 10px;
}
#panel {
width: 100%;
margin: 0 0 5px 0;
padding: 5px 0;
height: 55px;
border: 1px solid #ddd;
overflow: auto;
}
#out p {
padding: 0 5px;
margin: 0;
}
p.status {
color: green;
font-style: italic;
}
p.broadcast {
color: red;
font-weight: bold;
}
p.cc {
color: #999;
}
#input {
display: block;
width: 100%;
padding: 5px 0;
border: 1px solid #ddd;
}
</style>
</head>
<body>
<p>Socket chat</p>
<div id="panel">
<div id="out"></div>
</div>
<input type="text" id="input">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var chat = (function ($) {
var socket,
$panel,
$output,
$input;
function init () {
$panel = $('#panel');
$output = $('#out');
$input = $('#input');
$input.keypress(function (e) {
if (e.which == 13 && this.value) {
postMessage(this.value);
this.value = '';
e.preventDefault();
}
});
// TODO: failure handling
socket = io.connect('http://localhost');
socket.on('toClient', receiveMessage);
}
function postMessage (msg) {
socket.emit('toServer', {
type: 'post',
msg: msg
});
}
function receiveMessage (data) {
var msg = data.msg || JSON.stringify(data),
type = data.type;
$output.append('<p class="' + type + '">' + msg + '</p>');
scrollPanel();
}
function scrollPanel () {
var diff = $output.height() - $panel.height();
if (diff > 0) {
$panel.animate({scrollTop: '+=' + diff }, 300);
}
}
$(init);// init on domReady
// export nothing
return {};
}(jQuery));
</script>
</body>
</html>
@johnhunter
Copy link
Author

This is a basic chat server using node.js with the socket.io and express modules.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment