Skip to content

Instantly share code, notes, and snippets.

@feesta
Created October 3, 2012 17:00
Show Gist options
  • Save feesta/3828315 to your computer and use it in GitHub Desktop.
Save feesta/3828315 to your computer and use it in GitHub Desktop.
A basic NodeJS/Socket.IO chatroom
var express = require("express"),
http = require("http");
var app = express();
var server = http.createServer(app);
var io = require("socket.io").listen(server);
server.listen(80);
app.get("/", function (req, res) {
res.sendfile(__dirname + "/index.html");
});
io.sockets.on("connection", function (socket) {
socket.emit("from server", { message: "Welcome to Jeff's Chat Room!" });
sendAll({online: Object.keys(socket.manager.open).length});
socket.on("from client", function (data) {
console.log("received: ", data, " from ", socket.store.id);
if (data.message)
sendAll(data, socket.id);
});
socket.on("disconnect", function(reason) {
sendAll({online: Object.keys(socket.manager.open).length});
});
});
function sendAll(message, user) {
for (var socket in io.sockets.sockets) {
if (socket != user)
io.sockets.sockets[socket].emit("from server", message);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var socket = io.connect('/');
socket.on('from server', function (data) {
console.log(data);
if (data.message) {
//document.write(data.message);
$("#messages").append("<div>" + data.message + "</div>");
}
if (data.online) {
console.info("online:", data.online);
$("#onlinecount").html(data.online + " online");
}
});
$(function(){
$("#ui button").on("click", function(e){
var message = $("#textinput").val();
socket.emit('from client', { message: message });
$("#textinput").val("").focus();
$("#messages").append("<div class='ownmessage'>" + message + "</div>");
e.preventDefault();
});
$("#textinput").focus();
});
</script>
<style>
form {display:inline-block;}
body {font-family:sans-serif;}
#onlinecount {font-size:small; color:#999;}
#messages {color:#444; font-size:11px;}
#messages .ownmessage {font-weight:bold;}
</style>
</head>
<body>
<div id="ui">
<form>
<input id="textinput" placeholder="chat box" />
<button>send</button>
</form>
<span id="onlinecount">1 online</span>
</div>
<div id="messages"></div>
</body>
</html>
{
"name": "feesta-chatroom",
"description": "Basic NodeJS/Socket.IO chatroom",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x",
"socket.io": "*"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment