Python Socket编程简单的Web服务器 [英] Python Socket Programming Simple Web Server

查看:52
本文介绍了Python Socket编程简单的Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个 Python 套接字编程代码,但我无法弄清楚出了什么问题.我输入了运行该程序的服务器的 IP 地址以及端口号和我试图接收的文件.我应该在浏览器中收到文件并且套接字应该关闭.取而代之的是,服务器将打印行Ready to serve..."打印三遍,在浏览器上显示404 Not Found",并且永远不会关闭套接字.有人有什么想法吗?

I am working on my first Python socket programming code and I cannot figure out what is wrong. I type in the IP address of the server that this program is running on along with the port number and the file I am trying to receive. I should receive the file in the browser and the socket should close. Instead, the server prints out the print line 'Ready to serve...' three times, displays '404 Not Found' on the browser, and never closes the socket. Does anyone have any ideas?

#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() 

推荐答案

感谢大家的帮助.我想出了什么问题.我已将 HTML 重命名为HelloWorld.html",然后 Windows 自动将 .html 添加到文件末尾.因此,为了访问该文件,我需要输入 HelloWorld.html.html.我更改了文件名,然后此代码完美运行.

Thank you everyone for all the help. I figured out what was wrong. I had renamed my HTML to "HelloWorld.html" and then Windows automatically added .html to end of the file. So in order to have accessed the file I would of needed to type in HelloWorld.html.html. I changed the file name and then this code worked perfectly.

这篇关于Python Socket编程简单的Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆