socket 服務端 客戶端(注釋版)

2021-09-25 11:11:54 字數 2349 閱讀 6101

# !/usr/bin/env python

# -*- coding: utf-8 -*-

# @time : 2017/8/22 16:14

# @author : mr_zhang

# @site :

# @file : server.py

# @software: pycharm

from socket import *

import subprocess

import struct

phone = socket(af_inet,sock_stream)

phone.setsockopt(sol_socket,so_reuseaddr,1)

phone.bind(('127.0.0.1',8080))

phone.listen(7)

print('startting...')

while true:

conn,client_addr = phone.accept() #等待客戶端傳送資料 *****=>接收

print('------->',conn,client_addr)

while true:

try:

cmd = conn.recv(1024)

if not cmd:break

res = subprocess.popen(cmd.decode('utf-8'),shell=true, #將普通字串轉化為系統命令

stdout=subprocess.pipe,

stderr=subprocess.pipe)

stdout = res.stdout.read() #輸入正確讀取的內容

stderr = res.stderr.read() #輸入錯誤讀取的內容

header = struct.pack('i',len(stdout)+len(stderr)) #根據長度製作報頭

conn.send(header) #傳送報頭去探路

conn.send(stdout)

conn.send(stderr)

except exception:

break

conn.close()

phone.close()

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @time : 2017/8/22 16:14

# @author : mr_zhang

# @site :

# @file : client.py

# @software: pycharm

from socket import *

import struct

phone = socket(af_inet,sock_stream)

phone.connect(('127.0.0.1',8080))

while true:

cmd = input('>>:').strip() #輸入的命令

if not cmd:continue

phone.send(cmd.encode('utf-8')) #encode之後傳送出去

header_struct = phone.recv(4) #接收的報頭資訊

unpack_res = struct.unpack('i',header_struct) #將位元組流轉化為python資料型別

total_size = unpack_res[0] #拆包之後是元組,取第一項

recv_size = 0 #接收道德資料,剛開始為0

total_data = b'' #初始資料

while recv_size < total_size: #接收到的資料《總共的資料

recv_data = phone.recv(1024) #每次接收的資料

recv_size+=len(recv_data) #接收到的資料=每次接收的收據+上次接收的資料

total_data+=recv_data #最後的總資料

print(total_data.decode('gbk')) #轉換為本機電腦的編碼

phone.close()

服務端 客戶端Socket通訊

服務端 using system using system.collections.generic using system.net using system.net.sockets using system.text using system.text.regularexpressions usi...

socket 服務端於客戶端

usr bin env python coding utf 8 time 2017 8 23 15 33 author mr zhang site file 服務端.py software pycharm from socket import import subprocess,struct,jso...

基於socket簡易版客戶端,服務端互動

af unix 是基於檔案型別的套接字家族 af inet是 基礎網路型別的套接字家族 socket 模組屬性很多,可以直接使用from module import 語句 這樣socket所有的資料都被帶勁命名空間裡了.減少 量 少用 服務端 1匯入 import socket 2.獲取套接字 s ...