DEV Community

Rishikesh-Programmer
Rishikesh-Programmer

Posted on

Socket.io Simple Chat App

Creating a real-time chat app with Socket.io and JavaScript involves both server-side and client-side implementation. Below, I'll guide you through creating a simple chat application using these technologies.

Prerequisites:

  • Node.js installed on your machine.

Step 1: Set Up Your Project

  1. Create a new directory for your project.
mkdir socketio-chat-app
cd socketio-chat-app
Enter fullscreen mode Exit fullscreen mode
  1. Initialize your project with npm.
npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install necessary dependencies.
npm install express socket.io
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Server-Side Code
Create a file named server.js for the server-side code.

// server.js
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.use(express.static(__dirname + '/public'));

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

  // Listen for chat messages
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg); // Broadcast the message to all connected clients
  });

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

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

Step 3: Create Client-Side Code
Create a directory named public in your project and inside it, create an HTML file index.html.

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Socket.io Chat App</title>
  <script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script>
</head>
<body>
  <ul id="messages"></ul>
  <form id="form" action="">
    <input id="m" autocomplete="off" /><button>Send</button>
  </form>

  <script>
    const socket = io();

    // Listen for chat messages
    socket.on('chat message', (msg) => {
      const messages = document.getElementById('messages');
      const li = document.createElement('li');
      li.textContent = msg;
      messages.appendChild(li);
    });

    // Send chat messages
    document.querySelector('form').addEventListener('submit', (e) => {
      e.preventDefault();
      const input = document.getElementById('m');
      if (input.value) {
        socket.emit('chat message', input.value);
        input.value = '';
      }
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Your Application
Run your server.

node server.js
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your web browser, and you should be able to see the chat application. Open multiple browser tabs to simulate different users and see real-time chat in action.

That's it! You've created a basic real-time chat application using Socket.io and JavaScript. Feel free to enhance it by adding features like user authentication, private messaging, or a better user interface.

Top comments (1)

Collapse
 
afifudinmtop profile image
Afifudin Maarif

thanks