一個簡單的python檔案傳輸伺服器
伺服器 程式碼,可以相容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!")