服务器 代码,可以兼容python2 和 python3
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from socket import socket, AF_INET, SOCK_STREAM
class 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_STREAM
target = ('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") #退出服务器
如果你跟我一样都喜欢python,想成为一名优秀的程序员,也在学习python的道路上奔跑,欢迎你加入python学习裙:python裙号:491308659 验证码:南烛 或者加扣扣1346525417
群内每天都会分享最新业内资料,分享python免费柯城,共同交流学习,让学习变(编)成(程)一种习惯!
网友评论