Chat server with node.js

I added the code for a chat server to the GitHub repository. It’s a simple server that someone wanted as an example to load to Azure. The main software is running an express server with on top. Message formats are JSON rather than plain text. The src file for the in the web page is served from the server on the express server. Code is below…

var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('').listen(server);
app.use(express.static(__dirname + "/public"));
// web port
var PORT = process.env.PORT || 8000;
io.on('connection', function (socket) {
  console.log('a user connected');
  socket.broadcast.emit('chat', {msg:"someone connected"});
  socket.emit('news', 'hello world');
  socket.on('chat', function (data) {
    console.log("Do some comands here...?");
    socket.broadcast.emit('chat', data);
  socket.on('disconnect', function () {
    console.log("someone disconnected");
    io.emit('chat',{msg:"someone disconnected"});
server.listen(PORT, function () {
  var port = server.address().port;
  console.log("App now running on port ", port);


<!DOCTYPE html>
  <input id="data"/>
  <input type="button" onclick="sendData()" value="SEND" />
  <a href="/">/</a>

var inputData = document.getElementById("data"); 
var logs = document.getElementById("log"); 
var socket = io(); 
socket.on('news', function (text) { 
socket.on('chat', function (data) { 
  var node = document.createElement("div");
// Create a node

  var textnode = document.createTextNode(data.msg); 
  node.appendChild(textnode); logs.appendChild(node); }); 
  // when the client clicks SEND 
  var sendData = function() { 
    var message = inputData.value; 
    inputData.value = ""; 
    // send server a 'dataIn' and send one parameter 
    socket.emit('chat', {msg: message}); 



Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s