作业 —— day36

1.编写 远程执行命令的CS架构软件

服务端:

import socket
import subprocess

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.bind(('127.0.0.1', 8081))
print('等待客户端连接...')
phone.listen(5)
while True:
    conn, address = phone.accept()
    print(f'客户端:{address}')
    try:
        while True:
            msg = conn.recv(1024)
            if len(msg) == 0:
                break
            print(f'客户端消息:{msg.decode("UTF-8")}')
            res = subprocess.Popen(msg.decode("UTF-8"))
            res = res.stdout.read().decode('gbk')
            if res:
                conn.send(res.encode('UTF-8'))
            else:
                conn.send('没有数据'.encode('UTF-8'))
    except Exception:
        conn.close()

客户端:

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

phone.connect(('127.0.0.1', 8081))

while True:
    msg = input("请输入要传的内容(按q退出):").strip()
    if msg.lower() == 'q':
        break
    if len(msg) == 0:
        continue
    phone.send(msg.encode('UTF-8'))
    msg = phone.recv(4096)
    print(f'{msg.decode("UTF-8")}')

phone.close()

2.明天上午默写

TCP 三次握手

95446DFCE918480E2D6C63ADA51F07B7

3C

TCP四次挥手

88878760B277161973BFDA75D515B1F4

4C

加上通信循环 与 链接循环之后的 TCP通信代码

# 服务端

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

phone.bind(('127.0.0.1', 8080))

phone.listen(5)  # 5指的是半连接池的大小
print('服务端启动完成,监听地址为:%s:%s' % ('127.0.0.1', 8080))

while True:
    conn, client_addr = phone.accept()

    while True:
        try:
            data = conn.recv(1024) 
            if len(data) == 0:
                break
            print("客户端发来的消息:", data.decode('utf-8'))
            conn.send(data.upper())
        except Exception:
            break

    conn.close()

phone.close()
# 客户端

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

phone.connect(('127.0.0.1', 8080))

while True:
    msg = input("输入要发送的消息>>>: ").strip()  # msg=''
    if len(msg) == 0: continue
    phone.send(msg.encode('utf-8'))
    print('======?')
    data = phone.recv(1024)
    print(data.decode('utf-8'))

phone.close()
posted @ 2020-04-20 22:59  轻描丨淡写  阅读(157)  评论(0编辑  收藏  举报