socket 服務端於客戶端

2021-09-25 11:11:54 字數 2400 閱讀 6293

#!/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,json

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() #等待鏈結,返回鏈結訊息和客戶端的ip和埠

print(conn,client_addr) #檢視列印資訊

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_dic = #製作報頭

header_json = json.dumps(header_dic) #序列化報頭

header_bytes = header_json.encode('utf-8') #序列化轉碼

conn.send(struct.pack('i',len(header_bytes)))

conn.send(header_bytes)

conn.send(stdout)

conn.send(stderr)

except exception:

break

conn.close()

phone.close()

#!/usr/bin/env python

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

# @time : 2017/8/23 15:34

# @author : mr_zhang

# @site :

# @file : 客戶端.py

# @software: pycharm

from socket import *

import struct,json

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')) #傳送出去的訊息需要轉碼

header_len = struct.unpack('i',phone.recv(4))[0] #接收到的訊息解包 ([0]表示元組中的第乙個值(報頭))

header_bytes = phone.recv(header_len) #接收到的後續包

header_json = header_bytes.decode('utf-8') #基於上一行進行轉碼

header_dic = json.loads(header_json) #飯序列化

total_size = header_dic['total_size'] #反序列化之後得到的header_dic中的total_size大小

recv_size = 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 22 16 14 author mr zhang site file server.py software pycharm from socket import import subprocess import ...

客戶端與服務端的Socket通訊

客戶端 public class client catch exception e public void start else catch exception e public static void main string args catch exception e 該執行緒專門用來迴圈讀取服...