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

时间:2017-12-12 02:27:35

标签: python sockets server

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

#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时,它会打印一个空字符串(#39;感谢您连接')。当我从telnet连接localhost 12345时它发送的信息很好,所以我不知道为什么我的客户端没有收到消息

任何想法。我是套接字编程的新手,我很乐意找到解决方案,所以我可以继续前进。

1 个答案:

答案 0 :(得分:0)

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

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)
    

进一步阅读:

希望它有效! :)