1 #!usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # auther:Mr.chen
4 # 描述:
5
6 import socket
7 import os
8 import threading
9 import time
10 import json
11 from user_users import PersonInfo
12
13 DIR = os.path.dirname(os.path.abspath(__file__))
14 DIR = DIR+'/Folder/'
15
16 TAG = True
17
18
19
20 def tcplink(conn,addr):
21 """
22 tcp請求分析函數
23 :param conn: tcp連接對象
24 :param addr: 連接地址
25 :return:
26 """
27 print ("收到來自{0}的連接請求".format(addr))
28 conn.send('與主機通信中...')
29 while TAG:
30 try:
31 data = conn.recv(4096)
32 time.sleep(1)
33 if not data:
34 break
35 else:
36 print (data)
37 if data == 'ls':
38 P.view_file(conn)
39 continue
40 action,filename = data.strip().split()
41 action = action.lower()
42 if action == 'put':
43 re = P.Recvfile(conn,filename)
44 if re == True:
45 print ("文件接收成功!")
46 else:
47 print ("文件接收失敗!")
48 elif action == 'get':
49
50 P.Sendfile(conn,filename)
51 elif action == 'login':
52 name, password = filename.split(',')
53 P = PersonInfo(name, password)
54 re = P.login()
55 if re == True:
56 conn.send('Ready!')
57 else:
58 conn.send('False!')
59 elif action == 'register':
60 name,password = filename.split(',')
61 P = PersonInfo(name, password)
62 re = P.register()
63 if re == True:
64 conn.send('Ready!')
65 else:
66 conn.send('False!')
67 else:
68 print ("請求方的輸入有錯!")
69 continue
70 except Exception,e:
71 print "tcplink處理出現問題",e
72 break
73
74
75
76
77 if __name__ == '__main__':
78 host = 'localhost'
79 port = 8888
80 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
81 s.bind((host,port))
82 s.listen(5)
83 print ("服務運行中:正在監聽{0}地址的{1}端口:".format(host,port))
84 while TAG:
85 # 接受一個新連接
86 conn,addr = s.accept()
87 # 創建一個新線程處理TCP連接
88 t = threading.Thread(target=tcplink,args=(conn,addr))
89 t.start()
1 #!usr/bin/env python
2 # -*- coding:utf-8 -*-
3 # auther:Mr.chen
4 # 描述:
5
6 import time
7 import os
8 import pickle
9
10
11 class PersonInfo:
12 """
13 用戶模型類
14 """
15 DIR = os.path.dirname(os.path.abspath(__file__))
16 DIR = DIR + '/Folder/'
17 ConfigDir = DIR.replace('Folder','db')
18
19 def __init__(self,name,password):
20 self.Name = name #用戶名
21 self.Password = password #密碼
22 self.DIR = PersonInfo.DIR + self.Name +'/' #用戶家目錄
23
24
25 def login(self):
26 """
27 用戶登陸
28 :return:
29 """
30 dict = PersonInfo.config_read()
31 if dict == None:
32 return False
33 if self.Name in dict:
34 if dict[self.Name] == self.Password:
35 return True
36 return False
37
38
39
40 def register(self):
41 """
42 用戶注冊
43 :return:
44 """
45 if os.path.exists(self.DIR) != True:
46 os.system('mkdir'+' '+ self.DIR)
47 try:
48 dict = PersonInfo.config_read()
49 if dict == None:
50 dict = {}
51 if self.Name not in dict:
52 dict[self.Name] = self.Password
53 else:
54 print ("姓名重復")
55 return False
56 re = PersonInfo.config_write(dict)
57 if re == True:
58 return True
59 except Exception,e:
60 print "注冊出現異常!",e
61 return False
62
63
64
65 def view_file(self,conn):
66 """
67 查看用戶家目錄
68 :param conn:
69 :return:
70 """
71 data = os.popen('ls'+' '+ self.DIR).read()
72 conn.sendall(data)
73
74 def Recvfile(self,conn,filename):
75 """
76 接收文件方法
77 :param conn:tcp連接對象
78 :param filename:目標文件名
79 :return:
80 """
81 print ("開始接收文件...")
82 conn.send('Ready!')
83 buffer = []
84 while True:
85 d = conn.recv(4096)
86 if d == 'exit':
87 break
88 else:
89 buffer.append(d)
90 data = ''.join(buffer)
91 if data == '':
92 return False
93 print (data)
94 print (filename)
95 print (self.DIR)
96 with open(self.DIR + filename, 'w') as f:
97 f.write(data)
98 return True
99
100
101 def Sendfile(self,conn,filename):
102 """
103 放送文件方法
104 :param conn: tcp連接對象
105 :param filename: 目標文件名
106 :return:
107 """
108
109 if os.path.exists(self.DIR + filename):
110 print ("開始放送文件...")
111 conn.send('Ready!')
112 time.sleep(1)
113 with open(self.DIR + filename, 'r') as f:
114 while True:
115 data = f.read(4096)
116 print (data)
117 if not data:
118 break
119 conn.sendall(data)
120 time.sleep(1)
121 conn.send('exit')
122 print ("文件放送成功!")
123 else:
124 conn.send('False!')
125
126
127 @staticmethod
128 def config_read():
129 """
130 配置文件全部讀取
131 :return:
132 """
133 if os.path.exists(PersonInfo.ConfigDir+'user_config'):
134 with open(PersonInfo.ConfigDir+'user_config','r') as f:
135 dict = pickle.load(f)
136 return dict
137
138
139 @staticmethod
140 def config_write(dict):
141 """
142 配置文件全部寫入
143 :param dict:
144 :return:
145 """
146 with open(PersonInfo.ConfigDir + 'user_config', 'w') as f:
147 pickle.dump(dict,f)
148 return True
#!usr/bin/env python
# -*- coding:utf-8 -*-
# auther:Mr.chen
# 描述:
import socket,os
import time
TAG =True
DIR = os.path.dirname(os.path.abspath(__file__))
DIR = DIR+'/Folder/'
HOST = 'localhost'
PORT = 8888
def Recvfile(s,filename):
"""
接收文件方法函數
:param s: 套接字封裝對象
:param filename: 目標文件名
:return:
"""
print ("開始下載文件...")
buffer = []
while TAG:
d = s.recv(4096)
if d == 'exit':
break
buffer.append(d)
data = ''.join(buffer)
with open(DIR+filename,'w') as f:
f.write(data)
print ("文件下載完畢!")
def Sendfile(s,filename):
"""
放送文件方法函數
:param s: 套接字封裝對象
:param filename: 目標文件名
:return:
"""
print ("開始上傳文件!")
if os.path.exists(DIR+filename):
with open(DIR+filename,'r') as f:
while TAG:
data = f.read(4096)
if not data:
break
s.sendall(data)
time.sleep(1)
s.send('exit')
print ("文件上傳完畢")
else:
print ("你的目錄里沒有這個文件")
time.sleep(1)
s.send('exit')
def Confirm(s,command):
"""
驗證與服務器連接是否正常;
把用戶命令發過去,讓服務器做好相應准備准備
:param s: 套接字封裝對象
:param command: 用戶輸入的命令
:return:
"""
s.sendall(command)
re = s.recv(4096)
if re == 'Ready!':
return True
elif re == 'False!':
return False
else:
print ("與服務器連接出現異常!")
def File_transfer(s):
"""
用戶指令函數
:param s:
:return:
"""
while TAG:
command = raw_input("請輸入你想執行的命令>>")
if not command:
continue
if command.lower().strip() == 'help':
print ("請用'put'+'空格'+'文件名'的格式上傳文件")
print ("請用'get'+'空格'+'文件名'的格式下載文件")
print ("輸入'ls'查看用戶服務器家目錄")
continue
if command.lower().strip() == 'ls':
s.send('ls')
data = s.recv(4096)
print (data)
continue
try:
action,filename = command.strip().split()
action = action.lower()
except:
print ("您的輸入有誤!輸入help查看幫助文檔")
continue
if action == 'put':
re = Confirm(s,command)
if re == True:
Sendfile(s, filename)
else:
print ("對方服務器沒有准備好!")
break
elif action == 'get':
re = Confirm(s,command)
if re == True:
Recvfile(s, filename)
elif re == False:
print ("服務器家目錄沒有這個文件")
else:
print ("對方服務器沒有准備好!")
break
else:
print ("你輸入的命令有誤!輸入help查看幫助文檔")
def Login(s):
"""
用戶登錄
:param s:
:return:
"""
name = raw_input("請輸入你的用戶名:")
password = raw_input("請輸入你的密碼:")
command = 'login'+' '+ name + ',' + password
re = Confirm(s, command)
if re == True:
print ("登陸成功!")
File_transfer(s)
elif re == False:
print ("您的輸入有誤,請重新輸入!")
Login(s)
else:
print ("與服務器連接出現異常!")
def Register(s):
"""
用戶注冊
:param s:
:return:
"""
name = raw_input("請輸入你的用戶名:")
password = raw_input("請輸入你的密碼:")
Password = raw_input("請再次輸入密碼:")
if password != Password:
print ("你的密碼兩次輸入不一致,請重新輸入!")
Register(s)
command = 'register' + ' ' + name + ',' + password
print (command)
re = Confirm(s,command)
if re == True:
File_transfer(s)
elif re == False:
print ("用戶名重復,請重新輸入!")
Register(s)
else:
print ("與服務器連接出現異常!")
def Main(s,log = '未聯通主機...'):
"""
用戶登陸界面
:param s:
:param log:
:return:
"""
text = """
用戶登陸界面 {0}
1,用戶登陸
2,用戶注冊
""".format(log)
print (text)
choose = raw_input("請輸入索引進行選擇:")
if choose == '1':
Login(s)
elif choose == '2':
Register(s)
else:
print ("你的選擇有誤!")
if __name__ == "__main__":
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((HOST,PORT))
Main(s,s.recv(1024))
except Exception,e:
print "服務器連接不上....",e
finally:
s.close()