Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
INDIVIDUAL_MQTT/mqtt_broker.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
31 lines (25 sloc)
866 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from gmqtt import Client as MQTTClient | |
class MQTTBroker: | |
def __init__(self, host='127.0.0.1', port=1883): | |
self.host = host | |
self.port = port | |
self.clients = {} | |
async def start(self): | |
server = await asyncio.start_server(self.handle_client, self.host, self.port) | |
async with server: | |
await server.serve_forever() | |
async def handle_client(self, reader, writer): | |
# Simple broker logic here | |
addr = writer.get_extra_info('peername') | |
print(f"Connection from {addr}") | |
while True: | |
data = await reader.read(100) | |
if not data: | |
break | |
print(f"Received {data} from {addr}") | |
writer.close() | |
await writer.wait_closed() | |
if __name__ == '__main__': | |
broker = MQTTBroker() | |
asyncio.run(broker.start()) |