Python learning 9_ network programming (socket, socketserver)

socketRealization

serverend

import socket
import subprocess
import struct
import json
# Buy a mobile phone
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Insert phone card, port range 0-65535
# Look at the usage state of the port and enter netstat -an |findstr 8080 on the command line.
phone.bind(('127.0.0.1', 8081))
# Open the machine
phone.listen(3)  # The number of semi connected pools is limited.
print('server start...')
# Waiting for phone connection request
while True:  # Connection cycle
    conn, clinet_address = phone.accept()
    print(conn, clinet_address)
    while True:
        try:
            # Send and receive messages
            data = conn.recv(1024)  # Communication cycle
            if (len(data) == 0): break  # For Linux or Mac.
            # Use subprocess to get the result instead of printing it to the screen.
            obj = subprocess.Popen(data.decode('utf-8'),
                                   shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
            stdout = obj.stdout.read()
            stderr = obj.stderr.read()
            # Make a fixed length header first.
            header_dic = {
                'total_size': len(stdout) + len(stderr),
                'filename': 'a.txt'
            }
            header_json = json.dumps(header_dic)
            header_bytes = header_json.encode('utf-8')
            # Send the length of the header again (fixed 4 bytes).
            conn.send(struct.pack('i', len(header_bytes)))
            # Re sending Baotou
            conn.send(header_bytes)
            # Finally, send real data.
            conn.send(stdout)
            conn.send(stderr)
        except ConnectionResetError:  # Aiming at windows system
            break
    # Say goodbye
    conn.close()
# Hang up the phone
phone.close()

View Code

 

clientend

import socket
import struct
import json

# Buy a mobile phone
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Dial the phone number
phone.connect(('127.0.0.1', 8081))
while True:
    # Send a message
    msg = input('>>:').strip()  # 1.If empty msg=''
    if (len(msg) == 0): continue  # 3.Not allowed to empty
    # 2.Send empty, and allow empty, but the operating system does not empty, send the principle of local data copy operation
    #   Data is copied from application to operating system, operating system adapter card, sending data.
    phone.send(msg.encode('utf-8'))
    # Receive messages
    # First extract 4 bytes to extract header length.
    header_size = struct.unpack('i', phone.recv(4))[0]
    # The header is accurately collected according to the length of the header, and the header dictionary is extracted from the header.
    header_bytes = phone.recv(header_size)
    header_json = header_bytes.decode('utf-8')
    header_dic = json.loads(header_json)
    total_size = header_dic['total_size']
    # Last received data
    res = b''
    recv_size = 0
    while recv_size < total_size:
        data = phone.recv(1024)
        res += data
        recv_size += len(data)
    print(res.decode('gbk'))
# Hang up the phone
phone.close()

View Code

 

socketserverRealization

serverend

import socketserver


class MyTCPhandle(socketserver.BaseRequestHandler):
    def handle(self):
        while True:
            try:
                data = self.request.recv(1024)  # self.request<==>conn
                if len(data) == 0: break
                self.request.send(data.upper())
            except ConnectionResetError:
                break


if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 8081), MyTCPhandle)
    # Every time you receive a link, instantiate the MyTCPhandle class and trigger the handle method.
    server.serve_forever()

View Code

 

clientend

import socket

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8081))
while True:
    msg = input('>>:').strip()
    if (len(msg) == 0): continue
    phone.send(msg.encode('utf-8'))
    data = phone.recv(1024)
    print('Server side message:', data)
phone.close()

View Code

 

Leave a Reply

Your email address will not be published. Required fields are marked *