服务器 代码,可以兼容python2 和 python3
#!/usr/bin/python3
# -*- coding: utf-8 -*- from socket import socket, AF_INET, SOCK_STREAMclass SimpleServer:
def startServer(self,port): tcpSerSock=socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(("",port)) tcpSerSock.listen(5) while True: try: print("server start! waiting connect...") tcpCliSock,addr =tcpSerSock.accept() print("from client " + addr[0]) while True: filename_len = tcpCliSock.recv(1) if not filename_len: break try: filename_len = int(str(filename_len)) #python2 except: filename_len = int(filename_len.decode()) #python3 filename = tcpCliSock.recv(filename_len).decode("utf8") if(filename == "quit"): tcpCliSock.close() tcpSerSock.close() return with open(filename, 'wb') as f: while True: buf = tcpCliSock.recv(4096) if not buf: break else: f.write(buf) print("recv ["+filename+"] ok!") break except: pass finally: tcpCliSock.close() tcpSerSock.close()if __name__ == '__main__':
print("start server!") s = SimpleServer() s.startServer(1234) print("end server!")
==============================================================
客户端 只在python3下试过 python应该是不行的
#!/usr/bin/python3
# -*- coding: utf-8 -*- # 发送格式为 1字节的"文件名长度"+"文件名"+"二进制数据" # 如果文件名是 quit 那就退出import os
from socket import socket, AF_INET, SOCK_STREAMtarget = ('127.0.0.1',1234)
class SimpleClient:
def setHost(self, host, port): self.host = host self.port = port def __get_header (self,filename): leng = len(filename) #文件名长度 assert leng<250 return str(leng) + filename #头部 就是 “1字节的长度”+“文件名” def send(self,filepath): #生成文件头 filename = os.path.basename(filepath) header = self.__get_header(filename) s = socket(AF_INET, SOCK_STREAM) s.connect(target) s.send((header).encode()) #先发送头部 if(filepath == "quit"): print("close server over!!!") pass else: with open(filepath, 'rb') as f: #读取数据发送 while True: buf = f.read(4096) if (len(buf)>0): s.send(buf) else: break print("send over!!!") # result = s.recv(256).decode() # print("result:"+result) s.close()if __name__ == '__main__':
c = SimpleClient() c.setHost("127.0.0.1", 1234) c.send("D:/testpy/data/a.jpg") # 发送文件 # c.send("quit") #退出服务器