Advertisement
metalx1000

NodeJS - Basic Web Chat with Sockets

Feb 24th, 2015
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.08 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. browser="google-chrome"
  4. dir="node_webchat"
  5. mkdir $dir
  6. cd $dir
  7.  
  8. if [ ! -f "/usr/bin/nodejs" ]
  9. then
  10.   sudo apt-get install nodejs
  11. fi
  12.  
  13. npm install --save express@4.10.2
  14. npm install --save socket.io
  15.  
  16. cat << EOF > server.js
  17. var app = require('express')();
  18. var http = require('http').Server(app);
  19. var io = require('socket.io')(http);
  20.  
  21. app.get('/', function(req, res){
  22.   res.sendFile(__dirname + '/index.html');
  23. });
  24.  
  25. io.on('connection', function(socket){
  26.   socket.on('chat message', function(msg){
  27.     io.emit('chat message', msg);
  28.     console.log(msg); //for server monitoring.
  29.     //process.stdout.write(msg);
  30.  
  31.   });
  32. });
  33.  
  34. http.listen(3000, function(){
  35.   console.log('listening on *:3000');
  36. });
  37. EOF
  38.  
  39. cat << EOH > index.html
  40. <!doctype html>
  41. <html>
  42.   <head>
  43.     <title>Socket.IO chat</title>
  44.     <style>
  45.       * { margin: 0; padding: 0; box-sizing: border-box; }
  46.       body { font: 13px Helvetica, Arial; }
  47.       form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
  48.       form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
  49.       form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
  50.       #messages { list-style-type: none; margin: 0; padding: 0; }
  51.       #messages li { padding: 5px 10px; }
  52.       #messages li:nth-child(odd) { background: #eee; }
  53.     </style>
  54.   </head>
  55.   <body>
  56.     <ul id="messages"></ul>
  57.     <form action="">
  58.       <input id="m" autocomplete="off" /><button>Send</button>
  59.     </form>
  60.     <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
  61.     <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  62.     <script>
  63.       var socket = io();
  64.       \$('form').submit(function(){
  65.         socket.emit('chat message', \$('#m').val());
  66.         \$('#m').val('');
  67.         return false;
  68.       });
  69.       socket.on('chat message', function(msg){
  70.         \$('#messages').append(\$('<li>').text(msg));
  71.       });
  72.     </script>
  73.   </body>
  74. </html>
  75. EOH
  76.  
  77. $browser "http://127.0.0.1:3000" &
  78. $browser "http://127.0.0.1:3000" &
  79. nodejs server.js
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement