1. 程式人生 > >Python Socket

Python Socket

conn 操作 更改 ket size 處理 等待 while 主動

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 = 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