> For the complete documentation index, see [llms.txt](https://tokenomy.gitbook.io/boilerplate-code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tokenomy.gitbook.io/boilerplate-code/integrations/websocket.md).

# 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.

```bash
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.&#x20;

```typescript
// 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.

```tsx
// 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;
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tokenomy.gitbook.io/boilerplate-code/integrations/websocket.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
