[Python] Djnago websocket program which accept the send-all message and send-each message

Discussão em 'Python' iniciado por Stack, Setembro 11, 2024.

  1. Stack

    Stack Membro Participativo

    I have React UI like this, simply it accepts the message from server.

    import React,{useState,useRef,useEffect,createRef,forwardRef,useImperativeHandle,useContext,RefObject} from 'react';

    const WebSocketPage = forwardRef((props,ref) =>{
    const webSocketRef = useRef(null);
    const [messages,setMessages] = useState([]);
    useEffect(() =>{
    if (
    webSocketRef.current &&
    webSocketRef.current.readyState === WebSocket.OPEN
    ) {
    return;
    }
    webSocketRef.current = new WebSocket(`ws://127.0.0.1:8000/ws/chat/`);

    console.log("websocket",webSocketRef.current);
    console.log("websocket state",webSocketRef.current.readyState);

    const onOpen = () => {
    console.log("WebSocket Connected");
    };

    const onMessage = (e) => {

    const data = JSON.parse(e.data);
    setMessages((messages) => [...messages, data.message]);
    };

    const onError = (e) => {
    console.log("WebSocket Error: ", e);
    };

    const onClose = () => {
    console.log("WebSocket Disconnected");
    };

    webSocketRef.current.addEventListener("open", onOpen);
    webSocketRef.current.addEventListener("message", onMessage);
    webSocketRef.current.addEventListener("error", onError);
    webSocketRef.current.addEventListener("close", onClose);

    return () => {
    if (webSocketRef.current?.readyState === 1) {
    webSocketRef.current.removeEventListener("open", onOpen);
    webSocketRef.current.removeEventListener("message", onMessage);
    webSocketRef.current.removeEventListener("error", onError);
    webSocketRef.current.removeEventListener("close", onClose);
    webSocketRef.current?.close();
    }
    };
    },[]);

    return(

    <div>test test</div>)
    });

    export default WebSocketPage


    then, in the python/django server , I can send the data to UI.

    def handle(self, *args, **options):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
    'chat',
    {
    "type": "chat_message",
    "message": {"content":"mytestdada","id":20}
    }
    )


    It works, and It sends the messages to the every browsers.

    Now, I am a bit confused.

    When there is people (A,B,C,D,E)

    How can I proper use of channel_layer?


    • channel_layer.group_send should be use for sending all people?(A,B,C,D,E)


    • channel_layer.send should be used for a few people group(A,B)


    • how should I send to the only A?

    Continue reading...

Compartilhe esta Página