我在python中编写了一个简单的客户端和服务器,我没理由理解并运行客户端但是我有一个问题了解并运行服务器。
这是客户端的代码,可以正常使用:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 12345
sock.connect((host, port))
data = sock.recv(1024)
sock.close()
print("Message: ", data)
print("Finished successfully")
这是我的服务器,现在你会注意到 sock.accept()前面有两个变量 connection & addr 这就是我想要了解的内容?为什么我需要这两个变量?为什么我没有?为什么我需要有两个分配了相同功能的变量?当我运行此代码时,它工作正常:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 12345
sock.bind((host, port))
sock.listen(5)
while True:
print("Waiting for a connection...")
connection, addr = sock.accept()
#print("Incomming connection from", addr)
msg = b'This is a test.'
connection.send(msg)
connection.close()
break
print("Finished successfully")
但是,如果我删除一个变量,请说 addr :
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'localhost'
port = 12345
sock.bind((host, port))
sock.listen(5)
while True:
print("Waiting for a connection...")
connection = sock.accept()
#print("Incomming connection from", addr)
msg = b'This is a test.'
connection.send(msg)
connection.close()
break
print("Finished successfully")
我运行此代码,出错了?为什么我会收到此错误?
Traceback (most recent call last):
File "server.py", line 16, in <module>
connection.send(msg)
AttributeError: 'tuple' object has no attribute 'send'
我只是不明白这背后的逻辑?这两个变量分配了相同的功能,我不明白为什么我应该有两个相同的变量,能够做同样的事情?
答案 0 :(得分:0)
这是因为根据文件:
socket.accept()
接受连接。套接字必须绑定到一个地址并侦听连接。返回值是一对(conn,address),其中conn是可用于在连接上发送和接收数据的新套接字对象,address是绑定到连接另一端的套接字的地址。 < / p>
这意味着你需要在使用socket.accept()
时解压缩值,否则你会收到一个元组对象,所以
conn, address = socket.accept() # correct way
conn = socket.accept() # incorrect since conn here is a tuple