V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
im67
V2EX  ›  Python

py3 学习 socket 中约到的问题

  •  
  •   im67 · 2017-09-26 22:58:55 +08:00 · 1721 次点击
    这是一个创建于 2410 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我在做个作业,建立一个 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
    
    9 条回复    2017-09-27 16:45:10 +08:00
    NoAnyLove
        1
    NoAnyLove  
       2017-09-27 09:14:03 +08:00   ❤️ 1
    client 没有问题,server 代码有问题
    im67
        2
    im67  
    OP
       2017-09-27 11:04:06 +08:00
    @NoAnyLove 我隐隐约约也是感觉自己 server 端有问题,就是对 socketserver 这种封装程度很高的模块没弄清楚,回去再好好 debug 吧。
    NoAnyLove
        3
    NoAnyLove  
       2017-09-27 11:44:08 +08:00
    @im67 Orz,你需要的不是 debug,而是看文档和文档里面的例子。。。。。。Orz,所以你还是没发现你的拼写有问题吗啊? T_T
    petelin
        4
    petelin  
       2017-09-27 12:49:36 +08:00
    def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self): def handler(self):

    浪费 绳命
    topbandit
        5
    topbandit  
       2017-09-27 13:55:40 +08:00
    用 socket.sendall()
    im67
        6
    im67  
    OP
       2017-09-27 14:23:53 +08:00
    @petelin 多谢~
    im67
        7
    im67  
    OP
       2017-09-27 14:25:00 +08:00
    @NoAnyLove 啊啊啊啊啊 ……昨晚看到半夜也没发现那个拼写错误
    im67
        8
    im67  
    OP
       2017-09-27 14:25:29 +08:00
    @topbandit thanks anyway
    DevNet
        9
    DevNet  
       2017-09-27 16:45:10 +08:00
    @im67 下午遇见的同样的问题,看了一个小时,解决不了,LZ 解决了吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2313 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:12 · PVG 20:12 · LAX 05:12 · JFK 08:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.