ZBLOG

帮我写一个python即使通讯软件服务端和客户端,使用WebSocket

Sure! Here’s an example code for a simple WebSocket-based instant messaging system using Python on both client and server:

Server

import asyncio
import websockets

connected = set()

async def handle_client(websocket, path):
    # register current websocket as connected to the server
    connected.add(websocket)

    try:
        async for message in websocket:
            # when a message is received, broadcast it to all connected clients
            for conn in connected:
                if conn != websocket:
                    await conn.send(message)
    finally:
        # unregister the websocket from the connected set when it disconnects
        connected.remove(websocket)

async def start_server():
    async with websockets.serve(handle_client, "localhost", 8765):
        await asyncio.Future()  # keep the server running indefinitely

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(start_server())

This code creates a WebSocket server that listens on port 8765. When a client connects, it registers the client’s WebSocket connection in a set of connected clients. When a client sends a message, the server broadcasts it to all connected clients (except for the sender). Finally, the server runs indefinitely until a future object is completed.

Client

import asyncio
import websockets

async def receive_messages():
    async with websockets.connect('ws://localhost:8765') as websocket:
        while True:
            # wait for incoming messages and print them to the console
            message = await websocket.recv()
            print('> Received message: %s' % message)

async def send_message():
    async with websockets.connect('ws://localhost:8765') as websocket:
        while True:
            # read user input and send it to the server
            message = input('> Send message: ')
            await websocket.send(message)

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(asyncio.gather(
        receive_messages(),
        send_message()))

This code creates a WebSocket client that connects to the server on localhost:8765. It then runs two coroutines, one for receiving messages and one for sending messages. The receive_messages coroutine listens for incoming messages from the server and prints them to the console. The send_message coroutine reads user input and sends it to the server. Both coroutines run indefinitely until the program is terminated.

That’s it! With these two code snippets, you should be able to run a simple WebSocket-based instant messaging system in Python.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1982

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?