首页 > 代码库 > Python Socket

Python Socket

 

 

Socket_server:

import socket
import os

port = 9000
host = "127.0.0.1"
ADDR = (host, port)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:

    server.bind(ADDR)
    server.listen(5)

    while True:
        print("Ready For Connection!")
        conn,addr = server.accept()
        while True:
                print("Read For Receive")
                try:                                      #当远程主机主动关闭后,再次conn.recv会导致ConnectionResetError,采用try处理。
                    cmd = conn.recv(1024)
                    if not cmd:                           #如果发送命令为空,说明断开连接
                        print("远程主机断开连接")
                        break
                    print("Received CMD:", cmd.decode())
                    cmd_result = os.popen(cmd.decode()).read()
                    if len(cmd_result) == 0:              #如果命令执行结果为空,避免等待,更改执行结果内容。
                        cmd_result = "Error:cmd has no output"
                    size = len(cmd_result.encode("utf-8"))  
                    conn.send(str(size).encode("utf-8"))     #发送执行结果大小
                    recv = conn.recv(1024)                   #如果client接收到大小,回馈OK信息。   如果两个send同时发送,会产生粘包,所以采用接受回送消息方式
                    print("Size Confirm",recv)
                    conn.send(cmd_result.encode("utf-8"))    #发送命令执行后的结果。
                except ConnectionResetError as e:
                    break

 

Socket_Client:

import socket
import sys

port = 9000
host = "127.0.0.1"
ADDR = (host, port)


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as clinet:
    clinet.connect(ADDR)
    while True:
        data_size = 0
        data = http://www.mamicode.com/b""
        cmd = input("操作命令:")
        if len(cmd) == 0:
            continue
        clinet.send(cmd.encode("utf-8"))
        result_size = clinet.recv(1024).decode()         #接收发送命令返回值大小
        clinet.send(b"OK")                                         #接受到返回值后,发送确认消息

        while data_size < int(result_size):
            data += clinet.recv(1024)
            data_size = len(data)

        print(data.decode())
        print("Result Size:%s, Received Size:%s" % (result_size, data_size))

  

 

Python Socket