socket io tutorial - Hello world with socket messages - socket io android - socket io client



"Hello world!" with socket messages

Install node modules

npm install express
npm install Socket io
click below button to copy the code. By Socket tutorial team

Node.js server

const express = require('express'); 
const app = express();
const server = app.listen(3000,console.log("Socket io Hello Wolrd server started!"));
const io = require('Socket io')(server);

io.on('connection', (socket) => {
    //console.log("Client connected!");
    socket.on('message-from-client-to-server', (msg) => {
        console.log(msg);
    })
    socket.emit('message-from-server-to-client', 'Hello World!');
});
click below button to copy the code. By Socket tutorial team

Browser client

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Hello World with Socket io</title>
  </head>
  <body>
    <script src="https://cdn.Socket io/Socket io-1.4.5.js"></script>
    <script>
      var socket = io("http://localhost:3000");
      socket.on("message-from-server-to-client", function(msg) {
          document.getElementById('message').innerHTML = msg;
      });
      socket.emit('message-from-client-to-server', 'Hello World!');
    </script>
    <p>Socker.io Hello World client started!</p>
    <p id="message"></p>
  </body>
</html>
click below button to copy the code. By Socket tutorial team
  • In the above example, the path to the Socket io library is defined as /Socket io/Socket io.js.

Even though we didn't write any code to serve the Socket io library, Socket io automatically does that.


Related Searches to Hello world with socket messages