使用TCPIP协议在Client端发送指令给Server端,并在Server端做出响应(类似聊天室)

Server端代码:

import asyncio
import socket
import win32api,win32con
import os,time

def setpanelcolor(inputcolor):
    username = os.environ.get("USERNAME")
    os.chdir(r'C:\Users\%s\Desktop' % username)
    os.system(r'start xxx.exe')
    time.sleep(2)
    # turn off panel diaplay
    win32api.keybd_event(113, 0, 0, 0)  # f2
    win32api.keybd_event(113, 0, win32con.KEYEVENTF_KEYUP, 0)
    time.sleep(2)
    # win32api.keybd_event(49, 0, 0, 0)#1
    # win32api.keybd_event(49, 0, win32con.KEYEVENTF_KEYUP, 0)
    if inputcolor == 'r':
        # 设置桌面为红色
        win32api.keybd_event(50, 0, 0, 0)  # 2
        win32api.keybd_event(50, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(3)
    if inputcolor == 'g':
        # 设置桌面为绿色

        win32api.keybd_event(51, 0, 0, 0)  # 3
        win32api.keybd_event(51, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(3)
    if inputcolor == 'b':
        # 设置桌面为蓝色
        win32api.keybd_event(52, 0, 0, 0)  # 4
        win32api.keybd_event(52, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(3)
    if inputcolor == 'w':
        # 设置桌面为蓝色
        win32api.keybd_event(56, 0, 0, 0)  # 8
        win32api.keybd_event(56, 0, win32con.KEYEVENTF_KEYUP, 0)
        time.sleep(3)


async def handle_echo(reader, writer):
    while True:
        data = await reader.read(1024)
        message = data.decode().strip()
        if message == 'exit':
            writer.close()
            break
        if message=='red':
            setpanelcolor('r')
        if message=='green':
            setpanelcolor('g')
        if message=='blue':
            setpanelcolor('b')
        if message=='white':
            setpanelcolor('w')

        print(f'Received: {message}')
        writer.write(data)
        await writer.drain()


async def main():
    server = await asyncio.start_server(
        handle_echo, '192.168.1.109', 12345)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()


asyncio.run(main())

客户端代码:

import socket

HOST = '127.0.0.1'  # The server's hostname or IP address
PORT = 8888  # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.connect((HOST, PORT))

    while True:
        message = input("Enter message (exit to quit): ")
        if message == 'exit':
            break
        sock.sendall(message.encode())

        received = sock.recv(1024)
        print("Received:", received.decode())

以上为单机端,本机操作,如果改为实际操作则要修改对应的IP

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值