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 socket.io on top. Message formats are JSON rather than plain text. The src file for the socket.io in the web page is served from the socket.io server on the express server. Code is below…

Server
var express = require('express')
, http = require('http');
//make sure you keep this order
var app = express();
var server = http.createServer(app);
var io = require('socket.io').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(data.msg);
    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);
});

Client

<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
  <input id="data"/>
  <input type="button" onclick="sendData()" value="SEND" />
  </a>
  <a href="/socket.io/socket.io.js">/socket.io/socket.io.js</a>

<script>
var inputData = document.getElementById("data"); 
var logs = document.getElementById("log"); 
var socket = io(); 
socket.on('news', function (text) { 
  console.log(text); 
}); 
socket.on('chat', function (data) { 
  console.log(JSON.stringify(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}); 
  }; 
</script>
</body>
</html>

 

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s