推荐学习书目
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
xcc7624
V2EX  ›  Python

python 的 socket.recv 的返回值的疑问(用 markdown 重写了一次主题)

  •  
  •   xcc7624 · May 26, 2016 · 3969 views
    This topic created in 3714 days ago, the information mentioned may be changed or developed.

    #socket 的 API 文档

    python socket

    socket.recv(bufsize[, flags])


    Receive data from the socket. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.


    这里说 return value is a string representing 是什么意思?如下的程序,客户端为什么 print data 打印出的是乱码,这个不是 ASCII 码表示的 510 吗?

    -------------------------------------客户端-------------------------

    # Echo server program
    import socket
    
    HOST = ''                 # Symbolic name meaning all available interfaces
    PORT = 50007              # Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    print 'Connected by', addr
    while 1:
        data = conn.recv(1024)
        if not data: break
        conn.sendall(data)
    conn.close()
    

    ---------------------------------服务器端--------------------------------------

    # Echo client program
    import socket
    
    HOST = '127.0.0.1'    # The remote host
    PORT = 50007              # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.sendall('\x05\x01\x00')
    data = s.recv(1024)
    s.close()
    
    print data
    print 'Received', repr(data)
    
    3 replies    2016-05-26 22:01:03 +08:00
    hahastudio
        1
    hahastudio  
       May 26, 2016   ❤️ 1
    1. The return value is a string representing the data received.
    返回值是一个字符串,表示接收的数据
    2. https://en.wikipedia.org/wiki/ASCII
    你的输入在 ASCII 里是 Enquiry, Start of Heading, Null 。
    如果你想提供字面量 510 作为输入,请 sendall("510") 或者 sendall("\x35\x31\x30")
    sujin190
        2
    sujin190  
       May 26, 2016   ❤️ 1
    再去查查 ascii 表吧,哪里发送 510 了
    xcc7624
        3
    xcc7624  
    OP
       May 26, 2016
    这样啊明白了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5627 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 03:46 · PVG 11:46 · LAX 20:46 · JFK 23:46
    ♥ Do have faith in what you're doing.