Friday, 5 October 2018

node express + socket.io

3 guys join the real-time chat hosted on 1 server (duplicated web pages). 
They send messages to server. 

server assign IDs to connected clients and broadcast received data to all connections.


package.json

{
  "name": "socketio",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ejs": "^2.6.1",
    "express": "^4.16.3",
    "jquery": "^3.3.1",
    "socket.io": "^2.1.1"
  }
}

-----------------------------------

server.js

const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const bodyParser = require('body-parser');
const exphbs = require('ejs');


const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, 'index.html');

const app = express();

app.set('view engine', 'ejs');

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', (req, res) => res.render('index'));

const server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

const io = socketIO(server);

let clientNum = 0;

io.on('connection', (socket) => {

  clientNum++;
  let currentTime = new Date();
  const socketId = socket.id;

  const connectionRes = currentTime.toLocaleString() + ' ' + 
      socketId + ' connected. ' +clientNum.toString() + ' online';

  console.log(connectionRes);

  //send to self when connected
  io.to(socketId).emit('server_connect', connectionRes);

   //response to client send event
  socket.on('client_chat', data=>{
    currentTime = new Date();

    //send to everyone except self
   socket.broadcast.emit('server_chat', 
     {
       name: data.name==''? socketId.toString() : data.name,
       message: data.message,
     }); 
   })


  socket.on('disconnect', () => {
    clientNum--;
    currentTime = new Date();

    console.log(currentTime.toLocaleString(), 
      'client disconnected. users', clientNum);
  });
});

-----------------------------------------

index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width-device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"/>
    <title>socket.io chat</title>
</head>
<body>
        <p id='connectionStatus'></p>

        <div style="height:300px;
                 background-color: lightgray;
                 overflow: scroll"
                 id = 'chatDialog'
                 >
        </div>

        <input placeholder='Name' id='name'/>
        <br/>

        <textarea style="width:350px; height:100px" placeholder='Message'
             id='message'></textarea>
        <br/>

        <button onclick='sendMessage()'>send</button>
        
        <script src="/socket.io/socket.io.js"></script>
        <script>
          var socket = io();
          var nameInput = document.getElementById('name');
          var messageInput = document.getElementById('message');
          var connectionStatus = document.getElementById('connectionStatus');
          var chatDialog = document.getElementById('chatDialog');

          function sendMessage(){
            socket.emit('client_chat', {
                name: nameInput.value,
                message: messageInput.value,
            });

            chatDialog.innerHTML = chatDialog.innerHTML + '<div>' + 
            '<span style="color: green">me:</span> '
            + messageInput.value +
            '</div>'
          }

           socket.on('server_connect', function(data){
            connectionStatus.innerHTML = data;
          });

          socket.on('server_chat', function(data) {

            chatDialog.innerHTML = chatDialog.innerHTML + '<div>' + 
            '<span style="color: blue">' + data.name + ':</span> '
             + data.message +
            '</div>'

          });

        </script>
      </body>
</html>

-------------------------------------
reference:

No comments:

Post a Comment