کنار صفحه چت من یک بخش Notification قرار بده که هر کلاینتی که پیامش را ارسال نمود، یا هر…
- User
کنار صفحه چت من یک بخش Notification قرار بده که هر کلاینتی که پیامش را ارسال نمود، یا هر سروری که پیامش را ارسال نمود، یک پروفایل واحد تشکیل شود (مانند تلگرام و آیدی) و بتوان با آن شخص چت نمود
بهتر است یک باکس قرار داده شود که ما از طریق آی پی مثلا آی پی ویندوز کلاینت با آن ارتباط برقرار نموده و پروفایل (صفحه چت) آن باز شود و بتوانیم با آن شخص (IP) چت کنیم
code Server (Linux)
import asyncio import websockets import ssl
connected_clients = set()
async def handle_client(websocket, path):
اضافه کردن کلاینت به لیست کلاینتهای متصل
connected_clients.add(websocket) try: async for message in websocket:
وقتی پیامی دریافت میشود، آن را به همه کلاینتها ارسال میکنیم
print(f"Received message: {message}") await broadcast(message) finally:
حذف کلاینت در صورت قطع ارتباط
connected_clients.remove(websocket)
async def broadcast(message): if connected_clients: # اگر کلاینتی متصل است await asyncio.wait([client.send(message) for client in connected_clients])
تنظیمات SSL
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ssl_context.load_cert_chain(certfile="server.pem", keyfile="server.pem")
start_server = websockets.serve(handle_client, "192.168.88.240", 8765)
asyncio.get_event_loop().run_until_complete(start_server) print("Server started, waiting for clients...") asyncio.get_event_loop().run_forever()
Code Client (Windows):
import asyncio import websockets
async def chat_client(): uri = "ws://192.168.88.240:8765" # آدرس IP سرور لینوکس را بهدرستی وارد کنید
async with websockets.connect(uri) as websocket: print("Connected to the server.")
دریافت پیام آمادگی از سرور
message = await websocket.recv() print(f"Server: {message}")
حلقه برای ارسال و دریافت پیامهای چت
while True:
دریافت پیام از کاربر
msg = input("Enter message to send: ")
ارسال پیام به سرور
await websocket.send(msg)
دریافت و نمایش پیام از سرور
response = await websocket.recv() print(f"Server: {response}")
اجرای کلاینت
asyncio.get_event_loop().run_until_complete(chat_client())
Chat web (html) for both:
- Assistant