⛓️Websocket

Overview

WebSocket is a protocol that provides a two-way, full-duplex communication channel between a client and a server over a single, long-lived connection. It enables real-time, bi-directional communication between web browsers and servers, allowing for efficient and low-latency communication.

How to use

Here we use websocket. The installation method is as follows below.

Step 1: Install Dependencies

Install the socket.io-client package which allows you to communicate with the server-side WebSocket using Socket.IO.

yarn add socket.io-client

Step 2: Create a WebSocket Hook

Create a custom hook to handle the WebSocket connection. You can name it useWebSocket or any other preferred name. This hook will handle the WebSocket connection, sending and receiving messages.

// useWebSocket.ts
import { useEffect, useRef } from 'react';
import { io, Socket } from 'socket.io-client';

type WebSocketEvent = 'connect' | 'disconnect' | 'message';

type WebSocketHook = {
  socket: Socket | null;
  connected: boolean;
  connect: () => void;
  disconnect: () => void;
  sendMessage: (message: string) => void;
};

const useWebSocket = (): WebSocketHook => {
  const socketRef = useRef<Socket | null>(null);
  const connected = useRef(false);

  useEffect(() => {
    const socket = io(); // Initialize Socket.IO
    socketRef.current = socket;

    socket.on('connect', () => {
      connected.current = true;
    });

    socket.on('disconnect', () => {
      connected.current = false;
    });

    return () => {
      socket.disconnect();
      socketRef.current = null;
      connected.current = false;
    };
  }, []);

  const connect = () => {
    if (socketRef.current && !connected.current) {
      socketRef.current.connect();
    }
  };

  const disconnect = () => {
    if (socketRef.current && connected.current) {
      socketRef.current.disconnect();
    }
  };

  const sendMessage = (message: string) => {
    if (socketRef.current && connected.current) {
      socketRef.current.emit('message', message);
    }
  };

  return {
    socket: socketRef.current,
    connected: connected.current,
    connect,
    disconnect,
    sendMessage,
  };
};

export default useWebSocket;

Step 3: Use the WebSocket Hook in your Component

Use the useWebSocket hook in your Next.js component to interact with the WebSocket connection.

// pages/index.tsx
import React, { useState } from 'react';
import useWebSocket from '../hooks/useWebSocket';

const IndexPage: React.FC = () => {
  const [message, setMessage] = useState('');
  const { socket, connected, connect, disconnect, sendMessage } = useWebSocket();

  const handleConnect = () => {
    connect();
  };

  const handleDisconnect = () => {
    disconnect();
  };

  const handleSendMessage = () => {
    sendMessage(message);
  };

  return (
    <div>
      <h1>WebSocket Example</h1>
      <h2>Status: {connected ? 'Connected' : 'Disconnected'}</h2>
      <button onClick={handleConnect}>Connect</button>
      <button onClick={handleDisconnect}>Disconnect</button>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <button onClick={handleSendMessage}>Send Message</button>
    </div>
  );
};

export default IndexPage;

Last updated