python網(wǎng)絡(luò)編程--socket簡(jiǎn)單實(shí)現(xiàn)

python網(wǎng)絡(luò)編程                                                                                                                                    

成都創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都做網(wǎng)站、網(wǎng)站建設(shè)、甘南網(wǎng)絡(luò)推廣、小程序制作、甘南網(wǎng)絡(luò)營(yíng)銷、甘南企業(yè)策劃、甘南品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);成都創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供甘南建站搭建服務(wù),24小時(shí)服務(wù)熱線:13518219792,官方網(wǎng)址:muchs.cn

一、客戶端控制服務(wù)端執(zhí)行命令

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       #緩沖區(qū)大小為1KB
ADDR = (HOST,PORT)

tcp_ser_sock = socket(AF_INET,SOCK_STREAM)  #創(chuàng)建套接字對(duì)象,AF_INET表示面向網(wǎng)絡(luò)的,SOCK_STREAM表示用于TCP傳輸?shù)奶捉幼诸愋?tcp_ser_sock.bind(ADDR)     #將地址(主機(jī)名、端口號(hào)對(duì))綁定到套接字上
tcp_ser_sock.listen(5)  #設(shè)置并啟動(dòng)TCP 監(jiān)聽器,listen的參數(shù)表示連接被轉(zhuǎn)接或拒絕之前,傳入連接請(qǐng)求的最大數(shù)

while True:
    print('waiting for connecting...')
    tcp_cli_sock,addr = tcp_ser_sock.accept()   #返回一個(gè)socket對(duì)象和屬于客戶端的套接字
    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)   #解決粘包現(xiàn)象
        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()

網(wǎng)絡(luò)編程基礎(chǔ)知識(shí)

分享標(biāo)題:python網(wǎng)絡(luò)編程--socket簡(jiǎn)單實(shí)現(xiàn)
當(dāng)前地址:http://muchs.cn/article38/jpshpp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊(cè)網(wǎng)站建設(shè)、網(wǎng)站改版、移動(dòng)網(wǎng)站建設(shè)、建站公司網(wǎng)站設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)