Getting started with socketio in react

Install socketio:  

yarn add socket.io-client

useEffect initializes the connection and listens for messages pushed by the server

useEffect(() => {
    // 实例化socket对象
    socket.current = io('http://www.xxx.com', {
      query: {
        token: props.token.token,
      },
      transports: ['websocket'],
    })
    // 连接成功回调
    socket.current.on('connect', () => {
      setMessages([
        {
          id: nanoid(),
          msg: '您好有什么要咨询的吗',
          timestamp: new Date().getTime(),
          type: 'xiaozhitongxue',
        },
      ])
    })
    // 监听服务器推送的消息
    socket.current.on('message', (payload: ServerMessageType) => {
      setMessages((messages) => [
        ...messages,
        {
          id: nanoid(),
          msg: payload.msg,
          timestamp: Date.now(),
          type: 'xiaozhitongxue',
        },
      ])
    })
    return () => {
      socket.current?.close()
    }
  }, [])

Client pushes message to server

    socket.current?.emit('message', {
      msg: inputValue.trim(),
      timestamp: Date.now(),
    })

Summary: The client uses socket.on to receive messages from the server, and the client uses socket.emit to push messages to the server.

Supongo que te gusta

Origin blog.csdn.net/Suk__/article/details/129289760
Recomendado
Clasificación