1、#传输文件的例子
import socket
from socket import *
import os
import requests
import time,socketserver,struct,os,_thread
def conn_thread(conn,addr): while 1: try: conn.settimeout(600) fileinfo_size=struct.calcsize('30sl') buf=conn.recv(fileinfo_size) if buf: filename,filesize=struct.unpack('30sl',buf) filename_f=filename.decode().strip('\00') filenewname=os.path.join('e:\\',os.path.basename(filename_f)) print('文件名称:%s,文件大小:%s'%(filenewname,filesize)) recvd_size=0 file=open(filenewname,'wb') print('开始传输文件内容。。。') while not recvd_size==filesize: if filesize-recvd_size>1024: rdata=conn.recv(1024) recvd_size+=len(rdata) else: rdata=conn.recv(filesize-recvd_size) recvd_size=filesize print('type(rdata):',type(rdata)) file.write(rdata) file.close() print('receive done') except socket.timeout: conn.close() while 1:
sk=socket()
addr=('127.0.0.1',9999)
sk.bind(addr)
sk.listen(3)
print('开始进入监听状态:') conn,addr=sk.accept() print('连接来自:',addr) #t=threading.Thread(target=conn_thread,args=(conn,addr)) #t.start() _thread.start_new_thread(conn_thread,(conn,addr)) sk.close()
client 文件传输客户端代码:
from socket import * import os addr=('127.0.0.1',9999) #addr=('39.106.41.11',9999) sk=socket(AF_INET,SOCK_STREAM) sk.connect(addr)
#文件传输客户端
import os,struct #while 1: filepath=input('请输入要传输的文件路劲:') print(type(filepath)) print(len(filepath.encode())) if os.path.isfile(filepath): fhead=struct.pack('30sl',filepath.encode(),os.stat(filepath).st_size) print('文件大小为:',os.stat(filepath).st_size) sk.send(fhead) print('文件路径:',filepath) fp=open(filepath,'rb') while 1: filedata=fp.read(1024) if not filedata: break sk.send(filedata) fp.close() print('传输成功!') sk.close()
2、传输系统可执行的命令,服务端执行完成,返回客户端执行结果
server端:
import socket from socket import * import os import requests def get(url): return requests.get(url) sk=socket() addr=('127.0.0.1',9999) sk.bind(addr) sk.listen(3) while 1: print('连接开始了。。。。') conn,addr=sk.accept() print('来自客户端:',addr) data=conn.recv(1024).decode() print(data) com,pram=data.split() #result=eval("requests.get('"+data+"')") #result=requests.get(data) #result=eval(com+'('+'"'+pram+'"'+')') result=eval(com)(pram) conn.sendall(result.text[:1024].encode()) #注意一定要text,否则会卡在这里 conn.close() sk.close()
client 客户端传输命令:
from socket import * import os addr=('127.0.0.1',9999) sk=socket(AF_INET,SOCK_STREAM) sk.connect(addr) data='get http://www.sohu.com' sk.send(data.encode()) print(sk.recv(1024).decode()) sk.close()