Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import asyncio
- import json
- # The set of clients connected to this server. It is used to distribute
- # messages.
- clients = {} #: {websocket: name}
- chats = set()
- # { "chat_name" : [ ("time", "author", "massage") ] }
- messages = dict()
- users = {}
- @asyncio.coroutine
- def client_handler(websocket, path):
- print(path)
- print('New client', websocket)
- print(' ({} existing clients)'.format(len(clients)))
- # The first line from the client is the name
- data = yield from websocket.recv()
- print(data)
- data = json.loads(data)
- if data["chat"] not in chats:
- chats.add(data["chat"])
- if data["name"] not in users:
- users[data["name"]] = {"password": data["password"], "chats": [ data["chat"] ] }
- else:
- users[data["name"]]["chats"].append(data["chat"])
- yield from websocket.send('Welcome to websocket-chat {} , {}'.format(data["chat"], data["name"]) )
- clients[websocket] = data
- for client, _ in clients.items():
- if _["chat"] == data["chat"]:
- yield from client.send(data["name"] + ' has joined the chat '+ data["chat"])
- elif data["chat"] in chats:
- if data["name"] not in users:
- users[data["name"]] = {"password": data["password"], "chats": [ data["chat"] ] }
- yield from websocket.send('Welcome to websocket-chat {} , {}'.format(data["chat"], data["name"]))
- clients[websocket] = data
- for client, _ in clients.items():
- if _["chat"] == data["chat"]:
- yield from client.send(data["name"] + ' has joined the chat ' + data["chat"])
- else:
- if data["password"] == users[data["name"]]["password"]:
- yield from websocket.send('Welcome to websocket-chat {} , {}'.format(data["chat"], data["name"]))
- clients[websocket] = data
- for client, _ in clients.items():
- if _["chat"] == data["chat"]:
- yield from client.send(data["name"] + ' has joined the chat ' + data["chat"])
- else:
- yield from websocket.send('not correct password')
- # Handle messages from this client
- while True:
- # for i in chats:
- print(11)
- message = yield from websocket.recv()
- print(message)
- if message is None:
- their_name = clients[websocket]["name"]
- del clients[websocket]
- print('Client closed connection', websocket)
- for client, _ in clients.items():
- yield from client.send(their_name + ' has left the chat')
- break
- # Send message to all clients
- for client, _ in clients.items():
- print(str(client)+" clients[websocket][chat] " + str(clients[websocket]["chat"]) + " " + _["chat"])
- if str(clients[websocket]["chat"]) == _["chat"]:
- yield from client.send('{}: {}'.format(clients[websocket]["name"], message))
- LISTEN_ADDRESS = ('0.0.0.0', 8080)
- import websockets
- start_server = websockets.serve(client_handler, *LISTEN_ADDRESS)
- import asyncio
- asyncio.get_event_loop().run_until_complete(start_server)
- asyncio.get_event_loop().run_forever()
- 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement