Python Socket,pythonsocket

來源:互聯網
上載者:User

Python Socket,pythonsocket

 

 

Socket_server:

import socketimport osport = 9000host = "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 socketimport sysport = 9000host = "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))

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.