aquaballoon

Socket.IO

Jul 7th, 2014
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.68 KB | None | 0 0
  1. // package.json
  2. {
  3.   "name": "socket-chat-example",
  4.   "version": "0.0.1",
  5.   "description": "my first socket.io app",
  6.   "dependencies": {}
  7. }
  8.  
  9. $ npm install --save express
  10. $ npm install --save socket.io
  11.  
  12. // index.js
  13. var app = require('express')();    // import class (node_modules)
  14. var http = require('http').Server(app);
  15. var io = require('socket.io')(http);
  16.  
  17. app.get('/', function(req, res){  // localhost:3000/
  18.   res.sendfile('index.html');  
  19. });
  20.  
  21.  
  22. app.get('/link', function(req, res){  // localhost:3000/link
  23.   res.sendfile('link.html');
  24. });
  25.  
  26. io.on('connection', function(socket){  // connected to client
  27.   socket.on('chat message', function(msg){  // receiving 'message' from client
  28.   io.emit('chat message', msg);  // sending 'message' to client
  29.   });
  30. });
  31.  
  32. http.listen(3000, function(){  // port
  33.   console.log('listening on *:3000');
  34. });
  35.  
  36. //index.html
  37. <!doctype html>
  38. <html>
  39.   <head>
  40.     <title>Socket.IO chat</title>
  41.  
  42.     <script src="/socket.io/socket.io.js"></script>
  43.     <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
  44.  
  45.   </head>
  46.  
  47.   <body>
  48.  
  49.     <ul id="messages"></ul>
  50.  
  51.     <form action="">
  52.       <input id="m" />
  53.       <button>Send</button>
  54.     </form>
  55.  
  56.     <a href="link"> Link </a>
  57.    
  58.     <script>
  59.       var socket = io();  // io('127.0.0.1');
  60.  
  61.       $('form').submit(function(){
  62.         socket.emit('chat message', $('#m').val());  // sending message to server
  63.         $('#m').val('');
  64.         return false;  // Stopping the submit
  65.       });
  66.  
  67.       socket.on('chat message', function(msg){  // receiving message from server
  68.         $('#messages').append($('<li>').text(msg));
  69.       });
  70.  
  71.     </script>
  72.    
  73.   </body>
  74. </html>
Advertisement
Add Comment
Please, Sign In to add comment