gpt4 book ai didi

python - Python s.recv()返回空字符串

转载 作者:行者123 更新时间:2023-12-03 11:55:05 27 4
gpt4 key购买 nike

我在在线教程中找到了一个简单的客户端和服务器

#server.py        

import socket # Import socket module

s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
#client           # This is client.py file

import socket # Import socket module

s = socket.socket() # Create a socket object
host = 'localhost'
port = 12345 # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done

当我运行c lient.py时,它所做的就是在应打印时打印一个空字符串(“谢谢您的连接”)。当我从telnet连接localhost 12345时,它会很好地发送消息,所以我不知道为什么我的客户端没有收到消息

有什么想法吗。我是套接字编程的新手,很想找到一个解决方案,所以我可以继续。

最佳答案

按原样运行脚本时,出现此错误:

Waiting connections ...
Got connection from ('127.0.0.1', 63875)
Traceback (most recent call last):
File "serv.py", line 14, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'

这里的几件事:
  • 确保您发送的是bytes而不是str。您可以通过将第14行替换为:
    c.send(b'Thank you for connecting')
  • 同样,这样声明套接字s总是很有用的:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

  • 进一步阅读:
  • Py2:https://docs.python.org/2/library/socket.html
  • Py3:https://docs.python.org/3/library/socket.html

  • 希望它能起作用! :)

    关于python - Python s.recv()返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47764460/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com