【问题标题】:Simple TCP Server unable to connect简单 TCP 服务器无法连接
【发布时间】:2020-06-03 04:22:01
【问题描述】:

我正在学习网络入门课程,我们正在学习如何编写基本的 TCP 服务器。

我的设置: 该分配要求一个服务器,即一次处理一个 HTTP 请求的 Web 服务器。我的 Web 服务器应该“接受并解析 HTTP 请求,从服务器的文件系统中获取请求的文件,创建一个 HTTP 响应消息,该消息由请求的文件和标题行组成,然后将响应直接发送给客户端。如果请求文件不存在于服务器中,服务器应将 HTTP “404 Not Found”消息发送回客户端。”我用 Python 编写了服务器(见下文),据我所知,代码是准确的。在同一个目录中,我还创建了一个简单的 hello world html 文件,所以我有一些要求。

运行我的服务器: 当我运行代码时,终端期望“准备好服务...”消息并监听连接。这是正确的。

然后,当我在浏览器中输入 URL 时(我尝试了 http://localhost:1001http://localhost:1001/HelloWorld.html),浏览器说它无法连接。

Unable to connect screen from browser

我很确定我要么没有作为客户端正确连接到服务器,要么我的 Windows 机器没有正确设置,但是任何关于如何连接并将我的请求通过服务器的建议都会非常有用赞赏。

#import socket module
from socket import *
import sys # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

#Prepare a sever socket
serverPort = 1001
serverSocket.bind(('',serverPort))
serverSocket.listen(1)

while True:
    #Establish the connection
    print('Ready to serve...')
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024).decode()
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        #Send one HTTP header line into socket
        #Fill in start
        header = 'HTTP/1.1 200 OK\n'
        connectionSocket.send(header.encode())

        #Fill in end

        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i].encode())

        connectionSocket.send("\r\n".encode())
        connectionSocket.close()
    except IOError:
        #Send response message for file not found (404)
        #Fill in start
        error = 'HTTP/1.1 404 Not Found'
        connectionSocket.send(error.encode())
        #Fill in end

        #Close client socket
        #Fill in start
        connectionSocket.close()
        #Fill in end

serverSocket.close()
sys.exit()  #Terminate the program after sending the corresponding data

【问题讨论】:

  • 您在运行服务器时是否遇到绑定错误?你应该有。 1001是保留端口,和1024以下的所有端口一样。
  • 取决于他的环境,在 Windows 上,我在非管理员命令行上运行他的脚本没有问题。

标签: python networking server


【解决方案1】:

我刚刚尝试运行您的服务器,它运行正常。我尝试使用 url "http://localhost:1001/test.py" 获取 python 代码本身,然后我取回了你的代码。

您可能要检查的一些事情是您是否可以访问服务器的端口 1001。由于这不是标准端口,因此某些主机可能会阻止它。您可以尝试使用端口 80。

【讨论】:

  • 感谢您的建议。经过一番修改,我发现如果我使用端口 65535 并为我的主机换入 0.0.0.0,那么我可以专门让 Microsoft Edge(有趣的是不是 Chrome)分支到我的 HTTP/1.1 404 Not Found 错误。虽然这至少是一个开始,但我并不完全清楚为什么这些因素组合会有所帮助,并且特别想知道为什么 chrome 不起作用。我的 Try 分支中的错误似乎在 ' filename = message.split()[1] ' 语句中。这很奇怪,因为该声明是由教授在实验室的骨架代码中提供的。
猜你喜欢
  • 2014-09-12
  • 1970-01-01
  • 2017-08-04
  • 2023-01-30
  • 2017-02-24
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2012-07-30
相关资源
最近更新 更多