45 - Chat application with real-time messaging using WebSockets

Description

Create a chat application with real-time messaging using WebSockets, establishing a WebSocket connection to a server-side endpoint, displaying a chat interface with message history and user input, sending and receiving messages through the WebSocket connection, and updating the interface accordingly.

Algorithm

  1. Set up a WebSocket server-side endpoint

  2. Establish a WebSocket connection from the client-side to the server-side endpoint

  3. Display a chat interface with message history and user input

  4. Send messages from the client-side to the server-side through the WebSocket connection

  5. Receive messages from the server-side and update the chat interface accordingly

  6. Handle disconnections and reconnects

Classes

  • ChatApp: The main chat application component

  • ChatInterface: The chat interface component displaying message history and user input

  • WebSocketService: The service establishing and managing the WebSocket connection

Code

ChatApp.js

import React, { useState, useEffect } from 'react';
import ChatInterface from './ChatInterface';
import WebSocketService from './WebSocketService';

const ChatApp = () => {
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    WebSocketService.connect();
    setConnected(true);
  }, []);

  const handleSendMessage = (message) => {
    WebSocketService.send(message);
  };

  const handleReceiveMessage = (message) => {
    setMessages((prevMessages) => [...prevMessages, message]);
  };

  return (
    <div>
      <ChatInterface
        messages={messages}
        inputValue={inputValue}
        handleSendMessage={handleSendMessage}
        handleReceiveMessage={handleReceiveMessage}
      />
    </div>
  );
};

export default ChatApp;

ChatInterface.js

import React from 'react';

const ChatInterface = ({ messages, inputValue, handleSendMessage, handleReceiveMessage }) => {
  return (
    <div>
      <h2>Chat Interface</h2>
      <ul>
        {messages.map((message, index) => (
          <li key={index}>{message}</li>
        ))}
      </ul>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <button onClick={() => handleSendMessage(inputValue)}>Send</button>
    </div>
  );
};

export default ChatInterface;

WebSocketService.js

import WebSocket from 'ws';

const WebSocketService = {
  connect: () => {
    const socket = new WebSocket('ws://localhost:8080');
    socket.onmessage = (event) => {
      handleReceiveMessage(event.data);
    };
    socket.onopen = () => {
      console.log('Connected to WebSocket server');
    };
    socket.onclose = () => {
      console.log('Disconnected from WebSocket server');
    };
  },

  send: (message) => {
    socket.send(message);
  },
};

export default WebSocketService;

Explanation

The code establishes a WebSocket connection from the client-side to the server-side endpoint, displays a chat interface with message history and user input, sends and receives messages through the WebSocket connection, and updates the interface accordingly.

Possible Future Enhancements

  • Add support for multiple chat rooms

  • Add support for user authentication and authorization

  • Add support for file transfers

  • Improve performance and scalability

  • Integrate with a backend API for data persistence

Last updated