【发布时间】:2019-12-23 19:30:54
【问题描述】:
我一直在阅读Python - Network Programming 并尝试了代码。
查看不带括号的 print 语句,此代码适用于 Python 2。
由于我使用的是Python3,所以我对其进行了修改。
这是更新后的代码。
server.py
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # 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.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print(s.recv(1024))
s.close() # Close the socket when done
然后我按照教程中的说明运行这两个代码。
以下将在后台启动服务器。 $ python server.py &
一旦服务器启动,运行客户端如下:$ python client.py
这将产生以下结果 -
从 ('127.0.0.1', 48437) 获得连接谢谢您的连接
但是,我得到的输出略有不同。
最初我跑了python server.py。没啥事儿。
一旦我执行python client.py,我就会收到以下错误。
user@linux:~$ python server.py
Got connection from ('127.0.0.1', 59546)
Traceback (most recent call last):
File "server.py", line 16, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'
user@linux:~$
user@linux:~$ python client.py
b''
user@linux:~$
代码有什么问题以及如何解决?
【问题讨论】:
-
你需要对你的信息进行编码,
'Thank you for connecting'.encode()也是如此,在client.py中更改为recv(1024).decode() -
谢谢。有用!但是为什么需要对消息进行编码/解码呢?
-
@d-coder,我不知道通过网络传输时需要对消息进行编码/解码。顺便说一句,谢谢在这里找到答案。 quora.com/Why-is-encoding-needed?share=1
-
您下面的教程是为 Python 2 编写的(打开的页面显示 Python 2.4 [原文如此!])。你真的很想找到这十年的介绍。不再很难找到好的 Python 3 介绍材料。也许还可以参见nedbatchelder.com/text/unipain.html,以获得对这种特殊差异的基础的易于理解的解释。
-
@Sabrina :现在您知道为什么在通过网络发送消息时需要对消息进行编码。拍拍自己的背!干得好.. :)