【问题标题】:changing the port 80 if it was busy如果它很忙,请更改端口 80
【发布时间】:2021-01-05 11:51:45
【问题描述】:

我有一个任务是使用 LAN 在 TCP 上创建一个 Web 服务器,该项目是在端口 80 上向 localhost 发出请求,并在浏览器中显示“hi”,如果请求则显示“404 not found”错了,我有一个问题是端口 80 很忙,当使用除 80 之外的任何端口时它都会停止工作,分配的提示是“如果您在已经运行 Web 服务器的主机上运行服务器,那么您应该为您的 Web 服务器使用与端口 80 不同的端口。”我的代码是:

from socket import *

import os


def test():
    serverPort = 80
    serverSocket = socket(AF_INET, SOCK_STREAM)
    serverSocket.bind(('', serverPort))
    serverSocket.listen(1)

    print("web server on port", serverPort)

    while True:
        print("ready to serve")
        connectionSocket, addr = serverSocket.accept()
        try:
            message = connectionSocket.recv(1024)
            print(message)
            filename = message.split()[1]
            print(filename[1:])
            print(filename, '||', filename[1])
            f = open(filename[1:])
            outputdata = f.read()
            connectionSocket.send(outputdata.encode())
            connectionSocket.close()
        except Exception:
            print("404 Not Found")
            connectionSocket.send("""404 Not Found\r\n""".encode())
        pass
    pass

if __name__ == "__main__":
    test()  

【问题讨论】:

    标签: python localhost


    【解决方案1】:

    只需检查端口是否已在使用中

    def check(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        return s.connect_ex(('localhost', serverPort)) == 0
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 2011-12-14
      • 1970-01-01
      • 2013-02-08
      • 2022-11-16
      • 1970-01-01
      • 2014-09-19
      相关资源
      最近更新 更多