# Node.js Real-time App

Real-time chat application using services

* Node.js
    
* Express.js
    
* Socket.io
    
* VS-code
    

### Project Set-up

Open VS-Code editor and make a directory

```bash
mkdir chat-app
cd chat-app
npm init-y
```

npm is initialized in the directory, now you can check **npm --version**

Install Dependencies:  
Install dependencies Express.js for building the Web service and Socket.io for real-time communication.

```plaintext
npm install express socket.io
```

---

### Server Set-up

Create a file named 'server.js' and set up a basic Express.js server.

```javascript
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('A user connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});
```

In Summery, this code creates a web server using Express.js, sets up a WebSocket server using Socket.io for real-time communication, and defines routes and event handlers to serve HTML content and handle chat messages.

---

### Front-End Setup

Create an HTML file named 'index.html' for the frontend of our chat application

```xml
<!DOCTYPE html>
<html>
<head>
  <title>Simple Chat App</title>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    const socket = io();

    function sendMessage() {
      const message = document.getElementById('message').value;
      socket.emit('chat message', message);
      document.getElementById('message').value = '';
    }

    socket.on('chat message', (msg) => {
      const messages = document.getElementById('messages');
      const li = document.createElement('li');
      li.textContent = msg;
      messages.appendChild(li);
    });
  </script>
</head>
<body>
  <ul id="messages"></ul>
  <input id="message" autocomplete="off" />
  <button onclick="sendMessage()">Send</button>
</body>
</html>
```

### Run the Server

Start the server by running 'node server.js' in the terminal.

```bash
node server.js
```

---

## Test the Application

Open your web browser and navigate to 'http://localhost:3000'. You can open multiple browser tabs to simulate different users. Enter a message in the input field and click "Send". You should see the message appear in real-time in all open tabs.
