python网络编程                                                                                                                                    

一、客户端控制服务端执行命令

server:

#!/usr/local/python3/bin/python3.6
#-*- coding:utf-8 -*-
#AUTH:FJC
from socket import *
from time import ctime
import subprocess
HOST = ''           #HOST变量空白,表示可以使用任何地址
PORT = 21567
BUFSIZ = 1024       #缓冲区大小为1KB
ADDR = (HOST,PORT)

tcp_ser_sock = socket(AF_INET,SOCK_STREAM)  #创建套接字对象,AF_INET表示面向网络的,SOCK_STREAM表示用于TCP传输的套接字类型
tcp_ser_sock.bind(ADDR)     #将地址(主机名、端口号对)绑定到套接字上
tcp_ser_sock.listen(5)  #设置并启动TCP 监听器,listen的参数表示连接被转接或拒绝之前,传入连接请求的最大数

while True:
    print('waiting for connecting...')
    tcp_cli_sock,addr = tcp_ser_sock.accept()   #返回一个socket对象和属于客户端的套接字
    print('...connect from:',addr)
    while True:
        try:
            data = str(tcp_cli_sock.recv(BUFSIZ),'utf8')
        except Exception:
            break
        if not data:
            continue
        obj = subprocess.Popen(data,shell=True,stdout=subprocess.PIPE)
        result = obj.stdout.read()
        tcp_cli_sock.send(bytes(str(len(result)),'utf8'))
        tcp_cli_sock.recv(BUFSIZ)   #解决粘包现象
        tcp_cli_sock.send(result)
    tcp_cli_sock.close()
tcp_ser_sock.close()

client:

#-*- coding:utf-8 -*-
#AUTH:FJC
from socket import *
from sys import exit
HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcp_cli_sock = socket(AF_INET,SOCK_STREAM)
tcp_cli_sock.connect(ADDR)

while True:
    data = input('command>')
    if not data:
        continue
    elif data == ("exit" or "quit"):
        exit(1)
    tcp_cli_sock.send(bytes(data,'utf8'))
    result_len=str(tcp_cli_sock.recv(BUFSIZ),'utf8')
    tcp_cli_sock.send(bytes(1))
    result = bytes()
    while len(result) != int(result_len):
        data_rec = tcp_cli_sock.recv(BUFSIZ)
        result += data_rec
    print(str(result,'gbk'))
# tcp_cli_sock.close()
二、文件上传下载

server:

#-*- coding:utf-8 -*-
#AUTH:FJC
from socket import *
import os

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcp_ser_sock = socket(AF_INET,SOCK_STREAM)
tcp_ser_sock.bind(ADDR)
tcp_ser_sock.listen(5)

BASE_DIR=os.path.dirname(os.path.abspath(__file__))

def upload():
    file_size = str(tcp_cli_sock.recv(BUFSIZ), 'utf8')
    file_size = int(file_size)
    file_recv = 0
    with open(path, 'ab') as f:
        while file_recv != file_size:
            data = tcp_cli_sock.recv(BUFSIZ)
            f.write(data)
            file_recv += len(data)
def download():
    file_size = os.stat(path).st_size
    tcp_cli_sock.send(bytes(str(file_size), 'utf8'))
    file_send = 0
    with open(path, 'rb') as f:
        while file_send != file_size:
            data = f.read(1024)
            tcp_cli_sock.send(data)
            file_send += len(data)
if __name__ == '__main__':
    while True:
        print('waiting for connecting...')
        tcp_cli_sock, addr = tcp_ser_sock.accept()
        print('...connect from:', addr)
        try:
            up_down_info = str(tcp_cli_sock.recv(BUFSIZ), 'utf8')
            cmd, path = up_down_info.split('|')
            filename = os.path.basename(path)
            path = os.path.join(BASE_DIR, 'server_dir', filename)
            if cmd == 'get':
                download()
            elif cmd == 'post':
                upload()
        except Exception:
            continue
    tcp_cli_sock.close()

client:

#-*- coding:utf-8 -*-
#AUTH:FJC
from socket import *
from sys import exit
import os

HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

BASE_DIR=os.path.dirname(os.path.abspath(__file__))

def get():
    file_size = str(tcp_cli_sock.recv(BUFSIZ), 'utf8')
    print(type(file_size))
    file_size = int(file_size)
    file_recv = 0
    with open(path, 'ab') as f:
        while file_recv != file_size:
            data = tcp_cli_sock.recv(BUFSIZ)
            f.write(data)
            file_recv += len(data)
    print("文件下载成功!")
def post():
    file_size = os.stat(path).st_size
    tcp_cli_sock.send(bytes(str(file_size), 'utf8'))
    file_send = 0
    with open(path, 'rb') as f:
        while file_send != file_size:
            data = f.read(1024)
            tcp_cli_sock.send(data)
            file_send += len(data)
    print("文件上传成功!")

if __name__ == '__main__':
    while True:
        tcp_cli_sock = socket(AF_INET, SOCK_STREAM)
        tcp_cli_sock.connect(ADDR)
        command = input('(command|file)>')
        if not command:
            continue
        elif command == "exit" or command == "quit":
            exit(1)
        cmd,path = command.split('|')
        up_down_info = '%s|%s' % (cmd, path)
        filename = os.path.basename(path)
        tcp_cli_sock.send(bytes(up_down_info, 'utf8'))
        path = os.path.join(BASE_DIR, filename)
        if cmd == 'get':
            get()
        if cmd == 'post':
            post()
        tcp_cli_sock.close()
三、支持http并发请求,并支持设置rt
import socket
import threading
import time

def handle_request(client_socket):
    # 接收客户端请求数据
    request_data = client_socket.recv(1024).decode()
    print("Received request:\n", request_data)

    # 构建响应报文
    response_data = "HTTP/1.1 200 OK\r\nContent-Length: 17\r\n\r\ntest111111 sleep5"

    # 设置睡眠时间
    time.sleep(5)

    # 发送响应数据给客户端
    client_socket.sendall(response_data.encode())

    # 关闭客户端连接
    client_socket.close()

def start_server():
    # 创建 TCP 套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定地址和端口
    server_socket.bind(("127.0.0.1", 8080))

    # 监听连接
    server_socket.listen(5)
    print("Server listening on port 8080...")

    while True:
        # 接受客户端连接
        client_socket, client_address = server_socket.accept()
        print("Accepted connection from:", client_address)

        # 创建线程处理请求
        t = threading.Thread(target=handle_request, args=(client_socket,))
        t.start()

if __name__ == "__main__":
    start_server()

网络编程基础知识