python - 无法在 Python 中拆分元组对象:“元组”对象没有“拆分”属性
问题描述
当我尝试运行我的程序时,我收到如下所示的错误:
Traceback (most recent call last):
File "/Volumes/USER/server.py", line 15, in <module>
filename = message.split()[1]
AttributeError: 'tuple' object has no attribute 'split'
我尝试更改 filename = message.split()[0] 的值,但没有奏效。
#import socket module
import socket
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Prepare a sever socket
serverName = socket.gethostname()
serverPort = 1234
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
while True:
#Establish the connection
print('Ready to serve...')
connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recvfrom(1024)
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.read()
#Send one HTTP header line into socket
header = 'HTTP/1.1 200 OK\r\n' +\
'Connection: close\r\n' + \
'Content-Type: text/html\r\n' + \
'Content-Length: %d\r\n\r\n' % (len(outputdata))
connectionSocket.send(header.encode())
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode())
connectionSocket.close()
except IOError:
#Send response message for file not found
header = 'HTTP/1.1 404 Not Found\r\n\r\n'
connectionSocket.send(header.encode())
#Close client socket
connectionSocket.close()
serverSocket.close()
在与程序 server.py 相同的目录中,我有一个名为 helloworld.html 的文件,当我使用硬编码端口转到服务器的 IP 地址时应该加载该文件,当我转到文件时也会显示 404那不存在。前 (192.168.1.2:1234/helloworld.html)
解决方案
根据文档:
socket.accept()
接受连接。套接字必须绑定到一个地址并监听连接。返回值是一对
(conn, address)
,其中 conn 是一个新的套接字对象,可用于在连接上发送和接收数据,地址是绑定到连接另一端套接字的地址。
所以,在你的代码中,在你这样做之后
message = connectionSocket.recvfrom(1024)
filename = message.split()
message
变成一个元组(conn, address)
。
现在,元组没有方法split()
。只有字符串有这种方法。我认为您要做的是拆分地址-因此您必须首先获取元组的第二个元素(当然,这是一个字符串),然后再拆分:
filename = message[1].split()
推荐阅读
- python - Flask WT-Form 未通过验证
- macos - MacOS Catalina Adobe Premiere 操作不允许
- google-colaboratory - 分享一个独特版本的 google colab doc?
- linux - 如何编写 curl 命令以获取最近 10 分钟内更新的数据
- reactjs - 我将如何设置此模式以进行切换?
- css - 如何在正方形中垂直和水平居中文本
- python - 将 Numpy 数组转换为特定的二维形式
- gcc - gcc 的汇编器和变量类型(长度、符号)
- verilog - 时钟门控verilog代码无法正常工作
- python - predict() 缺少 1 个必需的位置参数:sklearn LinearRegression 中的“X”