所以我尝试像第一个组件中的代码一样创建 websocket :
import { useState,useEffect } from 'react'
import Routes from './components/routers/Routes'
function App() {
const ws=new WebSocket("ws://localhost:8000/");
useEffect(() => {
ws.send("some message");
ws.addEventListener('message',(event:any)=>{
console.log('message listened!')
})
}, []);
return (
<>
<FirstComponent/>
</>
)
}
export default App;
第二个组件代码是:
import { useState,useEffect } from 'react'
import Routes from './components/routers/Routes'
function App() {
let stid:string|null=localStorage.getItem('stationid')
const ws=new WebSocket("ws://localhost:8000/");
useEffect(() => {
ws.addEventListener('message',(event:any)=>{
console.log('message listened!')
})
}, []);
return (
<>
<SecondComponent/>
</>
)
}
export default App;
后端由 Django 编写,使用 Web Socket 通道。 我如何从客户端发送消息并在所有连接到 Web Socket 的客户端中接收消息??
您可以通过在套接字连接打开时在消费者类中创建一个组来实现这一点。 你的消费者.py
from channels.generic.websocket import AsyncWebsocketConsumer
class myConsumer(AsyncWebsocketConsumer):
async def connect(self):
path_components = self.scope["path"].strip("/").split("/") #assuming websocket url is "ws/app/<stationid>/"
id = path_components[-1]
await self.channel_layer.group_add(
id, #Id decides which all channels you want to add in a group. you can use stationid as your group name .
self.channel_name
)
await self.send_group("hello!!" ,id ) #sends message to all channels of group
await self.accept()
async def send_group(self, message, group):
# Send message to a specific group
await self.channel_layer.group_send(
group,
{
'type': 'chat.message',
'message': message
}
)
async def chat_message(self, event):
# Receive message from group
message = event['message']
# Send message to WebSocket
await self.send(text_data=message)
在前端
const { id } = useParams(); // asuming ur url localhost:5173/app/stationid/
const socket = new WebSocket(
`ws://localhost:8000/ws/app/${id}/`
);
socket.onopen = () => {
console.log("WebSocket connection opened");
};
socket.onmessage = (event) => {
console.log("Message from server:", event.data);
// recieve all messages here . you can make use of useEffect hook to update UI every time a message is received .
};
socket.onclose = () => {
console.log("WebSocket connection closed");
};
进行相应配置