Socket IO

Pre-Action

Server Side (NodeJS Express)

npm install socket.io

Client Side (React)

npm install socket.io-client

Connect

Client Side

  • When user enter the chatroom, the connection should be done and do it in the componentDidMount

import io from "socket.io-client";
const Chatroom = ()=>{
    // const [ws,setWs] = useState(io(`Your API Site`)); Don't do this
    const [ws,setWs]= useState(null);
    useEffect(()=>{
        setWs(io(`Your API SITE`));
    },[])
}
  • Remember not to do it in useState !!!!

Server Side

  • When new user is connected, new connection will be triggered !!!

  • Then we can implement the logic within connection scope

Send and Receive Message

Send(Client)

  • From above the example: client send an object which includes userId and text , and bookmark it as sendMessage

Receive (Server)

  • The server can receive userId and text based on the bookmark, and can do callback function, such as send the message back to client

Sent(Server)

  • The server send the object to client/clients which is bookmarked as getMessage

Receive(Client)

Client can receive userId and text based on the bookmark, and can do callback function

Room

Join Room

  • At the beginning, we should send the room information and user information ,such as room name, user Id

  • After the server receive the info, it will divide user into different information based room name or other information

Send Message to Room

  • After divided user into different groups, server can choose to send message to clients in the specific groups

  • Server send message to all client in Group A which is bookmarked as msg, so client in group B cannot receive

Quit Room

  • Firstly, the client request to quit room by sending message to server

  • Then, after the server receive the message , it will do leaving action

Disconnect

Client Side

  • Firstly, disconnect the connection in client side

Server Side

  • After the disconnection of client side, it can be detected by server side

  • If disconnection is triggered, Disconnected will be printed out automatically

Last updated

Was this helpful?