Advertisement
Guest User

Simple Node.js and socket.io example

a guest
Jul 26th, 2011
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.79 KB | None | 0 0
  1. Originally from
  2. http://mclear.co.uk/2011/01/30/real-time-mouse-activity-w-nodejs-sockets/
  3. adapted to socket.io 0.7
  4.  
  5. -----------server.js---------
  6. // Simple Node & Socket server
  7.  
  8. var http = require('http')
  9. , url = require('url')
  10. , fs = require('fs')
  11. , io = require('socket.io')
  12. , sys = require('sys')
  13. , server;
  14.  
  15. server = http.createServer(function(req, res){
  16. var path = url.parse(req.url).pathname;
  17. switch (path){
  18. case '/':
  19. res.writeHead(200, {'Content-Type': 'text/html'});
  20. res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
  21. res.end();
  22. break;
  23.  
  24. case '/json.js':
  25. case '/test.html':
  26. fs.readFile(__dirname + path, function(err, data){
  27. if (err) return send404(res);
  28. res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
  29. res.write(data, 'utf8');
  30. res.end();
  31. });
  32. break;
  33. default: send404(res);
  34. }
  35. }),
  36.  
  37. send404 = function(res){
  38. res.writeHead(404);
  39. res.write('404');
  40. res.end();
  41. };
  42. server.listen(8080);
  43.  
  44. // socket.io, I choose you
  45. var io = io.listen(server)
  46. , buffer = [];
  47.  
  48. io.sockets.on('connection', function(client){
  49. client.send({ buffer: buffer });
  50. client.broadcast.json.send({ announcement: client.id + ' connected' });
  51.  
  52. client.on('message', function(message){
  53. var msg = { message: [client.id, message] };
  54. buffer.push(msg);
  55. if (buffer.length > 15) buffer.shift();
  56. client.broadcast.json.send(msg);
  57. console.log(msg);
  58. });
  59. client.on('disconnect', function(){
  60. console.log('disconnect');
  61. client.broadcast.json.send({ announcement: client.id + ' disconnected' });
  62. });
  63. });
  64.  
  65. --------- test.html-------
  66. <!doctype html>
  67. <html>
  68. <head>
  69. <title>Multi Mouse - How many mice can I mouse eater eat?</title>
  70. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <!-- jquery -->
  71. <script src="/json.js"></script> <!-- for ie -->
  72. <script src="socket.io/socket.io.js"></script> <!-- sockets -->
  73. </head>
  74. <body>
  75. <h1> You can see my mouse!! ZOMG - <a href="http://www.youtube.com/watch?v=aFLcbBvTGns">Video explaining why I'm doign this</a></h1>
  76.  
  77. <script>
  78.  
  79. // some random color
  80. function randc(){
  81. colors = new Array('#FF0000','#00FF00','#0000FF','#00FFFF','#FF00FF','#C0C0C0');
  82. var color = colors[Math.floor(Math.random()*colors.length)]
  83. return color;
  84. }
  85.  
  86. // When a new message arrives..
  87. function message(obj){
  88. var data = obj.message[1].split(':');
  89. var x = data[0];
  90. var y = data[1];
  91. var userid = obj.message[0];
  92.  
  93. if($('#mouse_'+userid).length == 0 && userid != 'you') {
  94. var randcolor = randc();
  95. $('body').append('<div class="dot" style="background-color:'+randcolor+'" id="mouse_'+userid+'"/>'
  96. );
  97. }
  98.  
  99. // stops a dot being drawn for local user
  100. if (userid != 'you'){
  101. $('#mouse_'+userid).css({
  102. 'left' : x + 'px',
  103. 'top' : y + 'px'
  104. })
  105. }
  106. /*
  107. var el = document.createElement('p');
  108. if ('announcement' in obj) el.innerHTML = '<em>' + esc(obj.announcement) + '</em>';
  109. else if ('message' in obj) el.innerHTML = '<b>' + esc(obj.message[0]) + ':</b> ' + esc(obj.message[1]);
  110. document.getElementById('chat').appendChild(el);
  111. document.getElementById('chat').scrollTop = 1000000;
  112. */
  113.  
  114. }
  115.  
  116. // A function to define how we send data
  117. function send(){
  118. var val = document.getElementById('text').value;
  119. socket.send(val);
  120. message({ message: ['you', val] });
  121. document.getElementById('text').value = '';
  122. }
  123.  
  124. // When a mouse is moved
  125. window.onmousemove = function(event){
  126. message({ message: ['you', event.clientX+':'+event.clientY] });
  127. socket.send(event.clientX+':'+event.clientY);
  128. };
  129.  
  130. // replace <&> w/ &lt&&gt
  131. function esc(msg){
  132. return msg.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  133. };
  134.  
  135. // establish the socket connection
  136. // var socket = new io.Socket(null, {port: 8080, rememberTransport: false});
  137. // socket.connect();
  138. var socket = io.connect('http://vs165120.vserver.de:8080');
  139. socket.on('message', function(obj){
  140. if ('buffer' in obj){
  141. document.getElementById('form').style.display='none';
  142. document.getElementById('chat').innerHTML = '';
  143.  
  144. for (var i in obj.buffer) message(obj.buffer[i]);
  145. } else message(obj);
  146. });
  147. </script>
  148.  
  149. <div id="chat"><p>Connecting...</p></div>
  150. <form id="form" onsubmit="send(); return false">
  151. <input type="text" autocomplete="off" id="text"><input type="submit" value="Send">
  152. </form>
  153.  
  154. <style>
  155. .dot { height: 10px; width: 10px; background-color:#000000;position:absolute;left:0;top:0;}
  156. </style>
  157.  
  158. </body>
  159. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement