我在做个作业,建立一个 socket 客户端和一个 socket 服务端,客服端接受用户输入用户名和密码,发送到服务端验证。但是不知怎的好像客户端的数据就是传不过去,抄作业都抄不会…… Google 了好久也没答案。下面贴出代码,望各位大神能指点下方向.( Python3.5 pycharm 中运行)
**********
客户端 ftpclient.py
**********
import socket
import getpass
class Client(object):
def __init__(self,host,port):
self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建 socket 连接
self.sock.connect((host,port))
if self.auth():
self.interactive()
def auth(self):
'''
发送用户名密码至 socket 服务端验证
:return:
'''
retry_count = 0
while retry_count <3:
username = input("username:").strip()
if len(username) == 0:continue
passwd = input("password:").strip()
auth_str = "ftp_authentication|%s|%s"%(username,passwd)
self.sock.send(auth_str.encode('utf-8')) #这条消息好像没有发送到服务端
auth_feedback = self.sock.recv(1024) #进行到这一步的时候报错
if auth_feedback == "ftp_authentication::success":
print("\033[32;1mAuthentication Passed!\033[0m")
self.username = username #
self.cur_path = username #
return True
else:
print("\033[31;1mWrong username or password\033[0m")
retry_count +=1
else:
print("\033[31;1mToo many attempts,exit!\033[0m")
def interactive(self):
pass
if __name__ == "__main__":
s= Client('localhost',5678)
控制台输入和反馈:数据没有发送至服务端
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe C:/Users/Administrator/PycharmProjects/ftp_sample/ftpClient/ftpClient.py
username:234
password:1223
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/ftp_sample/ftpClient/ftpClient.py", line 33, in <module>
s= Client('localhost',5678)
File "C:/Users/Administrator/PycharmProjects/ftp_sample/ftpClient/ftpClient.py", line 8, in __init__
if self.auth():
File "C:/Users/Administrator/PycharmProjects/ftp_sample/ftpClient/ftpClient.py", line 19, in auth
auth_feedback = self.sock.recv(1024)
ConnectionAbortedError: [WinError 10053] 您的主机中的软件中止了一个已建立的连接.
服务端 ftpServer.py
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
exit_flag = False
def handler(self):
while not self.exit_flag:
print('hi')
msg = self.request.recv(1024)
print(msg) #打印从 client 发来的信息。但是一直没有传过来,费解!!!!
if not msg:
break
msg_parse = msg.split("|")
msg_type = msg_parse[0]
if hasattr(self,msg_type):
func = getattr(self,msg_type)
func(msg_parse)
else:
print("--\033[31;1mWrong msg type:%s\033[0m--" % msg_type)
def authentication(self,msg):
print('----auth----')
if __name__ == "__main__":
HOST,PORT ="127.0.0.1",5678
server =socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
server.serve_forever()
控制台反馈:一直在运行,没有任何输出,其实期待输出 print(msg)
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\python.exe C:/Users/Administrator/PycharmProjects/ftp_sample/ftpServer/ftpServer.py
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.