DEV Community

Farooq khan
Farooq khan

Posted on

"How to build a real-time chat application using TypeScript and Socket.io"

Real-time chat applications have become increasingly popular in recent years, allowing users to communicate instantly with each other regardless of their location. In this blog post, we will explore how to build a real-time chat application using TypeScript and Socket.io.

What is TypeScript?

TypeScript is a statically typed superset of JavaScript that adds optional types to the language. It provides developers with the ability to write cleaner and more maintainable code by catching errors at compile-time rather than runtime. TypeScript also allows for better code completion and navigation in integrated development environments (IDEs) like Visual Studio Code.

What is Socket.io?

Socket.io is a JavaScript library that enables real-time, bidirectional and event-based communication between clients and servers. It works by establishing a WebSocket connection between the client and server, allowing for instant communication without the need to constantly poll the server for updates. Socket.io also provides fallback mechanisms such as polling and long-polling for environments where WebSockets are not supported.

Setting up the project

To get started, we need to set up a new TypeScript project. You can do this by running the following commands in your terminal:

mkdir real-time-chat-app
cd real-time-chat-app
npm init -y
npm install --save-dev typescript ts-node nodemon @types/node
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Next, create a src directory and add a server.ts file with the following content:

import express from 'express';
import http from 'http';
import socketio from 'socket.io';

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

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

  socket.on('message', (message) => {
    console.log('Received message:', message);
    io.emit('message', message);
  });

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

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

In this code snippet, we create an Express server and a Socket.io instance. We then listen for connections and disconnections from clients, handling messages sent by clients and broadcasting them to all connected clients.

To run the server, add the following scripts to your package.json file:

"scripts": {
  "start": "nodemon --exec ts-node src/server.ts"
}
Enter fullscreen mode Exit fullscreen mode

You can then start the server by running npm start in your terminal.

Building the client-side application

For the client-side application, create a new HTML file called index.html and add the following content:

<!DOCTYPE html>
<html>
<head>
  <title>Real-time Chat App</title>
</head>
<body>
  <ul id="messages"></ul>
  <input id="messageInput" type="text" placeholder="Enter your message">
  <button id="sendButton">Send</button>

  <script src="https://cdn.socket.io/socket.io-4.2.0.min.js"></script>
  <script>
    const socket = io();
    const messages = document.getElementById('messages');
    const messageInput = document.getElementById('messageInput');
    const sendButton = document.getElementById('sendButton');

    sendButton.addEventListener('click', () => {
      const message = messageInput.value;
      socket.emit('message', message);
      messageInput.value = '';
    });

    socket.on('message', (message) => {
      const li = document.createElement('li');
      li.innerText = message;
      messages.appendChild(li);
    });
  </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this code snippet, we include the Socket.io client library and set up the client-side code to listen for messages sent by the server and allow users to send messages.

To run the client-side application, open the index.html file in a web browser. You should see a simple chat interface where you can send and receive messages in real-time.

Conclusion

In this blog post, we learned how to build a real-time chat application using TypeScript and Socket.io. By following the steps outlined above, you can create a basic chat application that allows users to communicate instantly with each other. Keep in mind that this is a simple example, and there are many ways to enhance and customize the application further.

If you're interested in learning more about TypeScript and Socket.io, I recommend checking out their official documentation and exploring more advanced features and functionalities. Real-time chat applications are a great way to showcase your skills as a developer and create engaging user experiences. Happy coding!

Top comments (0)