【问题标题】:Python Socket Programming Simple Web Server, Trying to access a html file from serverPython Socket 编程简单的 Web 服务器,试图从服务器访问一个 html 文件
【发布时间】:2019-09-17 14:18:33
【问题描述】:

所以,我正在尝试在 python 上创建一个简单的服务器,并尝试通过它访问同一目录中的 html 文件,但作为输出,我一直在准备服务... output

编辑: 将 HTML 文件(例如 HelloWorld.html)放在服务器所在的同一目录中。运行服务器程序。确定运行服务器的主机的 IP 地址(例如 128.238.251.26)。从另一台主机打开浏览器并提供相应的 URL。例如: http://128.238.251.26:6789/HelloWorld.html “HelloWorld.html”是您放置在服务器目录中的文件的名称。还要注意冒号后面的端口号的使用。您需要将此端口号替换为您在服务器代码中使用的任何端口。在上面的例子中,我们使用了端口号 6789。浏览器应该会显示 HelloWorld.html 的内容。如果省略 ":6789",浏览器将假定端口 80,并且只有当您的服务器正在侦听端口 80 时,您才会从服务器获取网页。 然后尝试获取服务器上不存在的文件。您应该会收到“404 Not Found”消息。

#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverSocket.bind(('', 12006))
serverSocket.listen(1)
while True:
    print 'Ready to serve...'
    #Establish the connection
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        f.close()
        #Send one HTTP header line into socket
        connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        connectionSocket.close()
    except IOError:
        #Send response message for file not found
        connectionSocket.send('404 Not Found')
        #Close client socket
        connectionSocket.close()
serverSocket.close() 

【问题讨论】:

  • 您的输出是标准输出,通过print 函数使用。你应该向你的服务器发出请求,你会得到正确的输出
  • 哦,谢谢,但我只是使用随机 IP 地址吗?
  • 没有。如果你的服务器在你的本地机器上,你应该使用localhost地址;如果没有,你应该使用你的服务器IP。您还应该指定一个端口。你的情况是12006。以localhost:12006为例
  • 我现在收到一个错误 ``` TypeError: a bytes-like object is required, not 'str' ``` 由这一行引起 ``` connectionSocket.send('HTTP/1.0 200好的\r\n\r\n') ```
  • 根据最后一条评论,这是TypeError: a bytes-like object is required, not 'str' 和许多类似问题的副本(只需谷歌这个与“socket”相关的错误)。

标签: python python-3.x sockets server python-requests


【解决方案1】:

您的输出是一个标准输出,通过print 函数使用。你应该向你的服务器发出请求,你会得到正确的输出

如果你的服务器在你的本地机器上,你应该使用localhost地址;如果没有,你应该使用你的服务器IP。您还应该指定一个端口。 12006 在你的情况下。以localhost:12006为例

另外socket.send 方法需要一个类似字节的对象。不是字符串

如果只是字符串literal,则应在第一个引号前添加b字符

例子:

connectionSocket.send(b'HTTP/1.0 200 OK\r\n\r\n')

如果是string 对象,你应该编码它:

connectionSocket.send(outputdata[i].encode())

查看documentation

【讨论】:

  • 感谢您的澄清,我要访问的是一个基本的 html hello world 文件,它会是一样的吗。
  • 您可以编辑您的问题(在通讯中)吗?我不明白你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多