我正在尝试建立一个仅由两个用户组成的聊天室。每个聊天室中应有一个用户,而另一个用户在每个聊天室中都是唯一的。更像是服务器一次与一个客户端聊天。 我遇到了一个问题。我的程序中当前正在发生的事情是,一旦有两个用户连接到服务器,它将所有消息发送给第二个用户(以后连接了用户)。
我正在使用memurai,因为它支持Windows的redis API。
这是我的consumer.py和两个试图与其通信的html文件。
Consumer.py
import asyncio
import json
from django.contrib.auth import get_user_model
from channels.consumer import AsyncConsumer
from channels.db import database_sync_to_async
from channels.generic.websocket import WebsocketConsumer
class WebConsumer(AsyncConsumer):
global server_conn
async def websocket_connect(self, event):
server_conn.append(self)
await self.send({
"type" : "websocket.accept"
})
other_user = self.scope['url_route']['kwargs']['username']
print(other_user)
user = self.scope['user']
print(user)
await self.send({
"type" : "websocket.send",
"text":"Hello World"
})
chat_room = str(user) + str(other_user)
print(event,' to ', chat_room)
self.chat_room = chat_room
await self.channel_layer.group_add(
chat_room,
self.channel_name
)
async def websocket_receive(self, event):
print('recieved', event)
print(event['text'])
await self.channel_layer.group_send(
self.chat_room,
{
'type':'chat_message',
'message': str(self.chat_room)
}
)
async def chat_message(self,event):
print('message',event)
await self.send({
"type":"websocket.send",
"text": event['message']
})
async def websocket_disconnect(self, event):
print('disconnected', event)
index.html
<html>
<head>
</head>
<script>
var endpoint = 'ws://127.0.0.1:8000/ws/sk'
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log('message',e)
}
socket.onerror = function(e){
console.log('error',e)
}
socket.onopen = function(e){
console.log('open',e)
socket.send('server1')
}
socket.onclose = function(e){
console.log('close',e)
}
const sendMsg = () => {
socket.send('hi bro wassup');
}
</script>
<body>
Hey
<button onclick='sendMsg()'>click</button>
</body>
</html>
index2.html
<html>
<head>
</head>
<script>
var endpoint = 'ws://127.0.0.1:8000/ws/sks'
var socket = new WebSocket(endpoint)
socket.onmessage = function(e){
console.log('message',e)
}
socket.onerror = function(e){
console.log('error',e)
}
socket.onopen = function(e){
console.log('open',e)
socket.send('server2')
}
socket.onclose = function(e){
console.log('close',e)
}
const sendMsg = () => {
socket.send('i cant see you');
}
</script>
<body>
Hey
<button onclick='sendMsg()'>click</button>
</body>
</html>
routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator
from main.consumer import WebConsumer
application = ProtocolTypeRouter({
'websocket':AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
path('ws/<username>',WebConsumer.as_asgi()),
]
)
)
)
})