Advertisement
Guest User

Untitled

a guest
May 27th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /////////////////////////////////////////////////////////////////////
  2. ///Server Code
  3. /////////////////////////////////////////////////////////////////////
  4.  
  5.  
  6. // Require HTTP module (to start server) and Socket.IO
  7. var http = require('http'), io = require('socket.io');
  8.  
  9. // Start the server at port 8080
  10. var server = http.createServer(function(req, res){
  11.  
  12.   // Send HTML headers and message
  13.   res.writeHead(200,{ 'Content-Type': 'text/html' });
  14.   res.end('<h1>Hello Socket Lover!</h1>');
  15. });
  16. server.listen(8080);
  17.  
  18. // Create a Socket.IO instance, passing it our server
  19. var socket = io.listen(server);
  20.  
  21. // Add a connect listener
  22. socket.on('connection', function(client){
  23.   console.log('Client Connected',event);
  24.   // Success!  Now listen to messages to be received
  25.   client.on('message',function(event){
  26.     console.log('Received message from client!',event);
  27.   });
  28.   client.on('disconnect',function(){
  29.     clearInterval(interval);
  30.     console.log('Server has disconnected');
  31.   });
  32.  
  33. });
  34.  
  35.  
  36.  
  37.  
  38.  
  39. /////////////////////////////////////////////////////////////////////
  40. ///Client Code
  41. /////////////////////////////////////////////////////////////////////
  42. var socket = new io.Socket('localhost',{
  43.   port: 8080
  44. });
  45. socket.connect();
  46.  
  47. // Add a connect listener
  48. socket.on('connect',function() {
  49.   console.log('Client has connected to the server!');
  50.   sendMessageToServer("Client Connected");
  51. });
  52. // Add a connect listener
  53. socket.on('message',function(data) {
  54.   console.log('Received a message from the server!',data);
  55. });
  56. // Add a disconnect listener
  57. socket.on('disconnect',function() {
  58.   console.log('The client has disconnected!');
  59. });
  60.  
  61. // Sends a message to the server via sockets
  62. function sendMessageToServer(message) {
  63.   socket.send(message);
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement