관리 메뉴

Silver Library (Archived)

Today I Learnt - Nestjs & Socket.io 본문

카테고리 없음

Today I Learnt - Nestjs & Socket.io

Chesed Kim 2023. 3. 25. 18:03
반응형

In this time, I tried using socket.io to let nestjs can work as server to receive and replies back to the client side.

To achieve this, I installed nestjs and react app on the same root directory.

 

As a part of testing purpose, I made up a simple real-time chat app as below.

 

1. For reactjs, nestjs, set .on and .off (connect, disconnet).

2. Be sure to set up cors: true, or you will see bunch of errors in real-time.

3. The port number should be the same. Or server side won't listen up the client's one.

// Nest.js
import { WebSocketGateway, WebSocketServer, SubscribeMessage, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({cors: true})
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;

  handleConnection(socket: Socket) {
    console.log('Client connected:', socket.id);
  }

  handleDisconnect(socket: Socket) {
    console.log('Client disconnected:', socket.id);
  }

  @SubscribeMessage('message')
  handleMessage(socket: Socket, message: string) {
    console.log('Received message:', message);
    this.server.emit('message', message);
  }


}
// React.js
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
import styled from 'styled-components';
import Skeleton from './Skeleton';
// import { useRef } from 'react';
// import SidebarWhole from './Sidebar';
const Chat = () => {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const socket = io('http://localhost:3001', {
    pingTimeout: 60000,
  });

  // Skeleton
  // https://stackoverflow.com/questions/69008820/websocket-connection-error-insufficient-resources

  // const chatBodyRef = useRef(null);


  useEffect(() => {
    // Subscribe to "message" event
    socket.on('message', handleMessage);

    // Unsubscribe from "message" event when component unmounts
    return () => {
      socket.off('message', handleMessage);
      // socket.disconnect('message', handleMessage);
    };
  }, []);

  const handleMessage = (message) => {
    setMessages((messages) => [...messages, message]);
  };

  const sendMessage = (event) => {
    event.preventDefault();
    socket.emit('message', input);
    setInput('');
  };

  return (
    // <SidebarWhole>
    <ChatWrapper>
    <Sidebar>
      <SidebarHeader>Telegram</SidebarHeader>
      <SidebarItem active>Chats</SidebarItem>
      <SidebarItem>Contacts</SidebarItem>
      <SidebarItem>Settings</SidebarItem>
    </Sidebar>
    <ChatContainer>
      <ChatHeader>
        <div>Telegram Chat</div>
        <div>Online</div>
      </ChatHeader>
      <ChatBody>
        {messages.map((message, index) => (
          <ChatMessage key={index}>
            {message}
          </ChatMessage>
        ))}
      </ChatBody>
      <ChatInputArea onSubmit={sendMessage}>
        <ChatInput
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Type a message..."
        />
        <ChatButton>Send</ChatButton>
      </ChatInputArea>
    </ChatContainer>
  </ChatWrapper>
  // </SidebarWhole>
);
};

export default Chat;

 

 

GitHub - mireu-san/nest-react-socketio: Feature testing purpose repository.

Feature testing purpose repository. Contribute to mireu-san/nest-react-socketio development by creating an account on GitHub.

github.com