我使用python的socket和epoll来创建一个Web服务器。 我的操作系统是Linux CentOS 6, 我的python版本是python 2.7.8。 我的源代码是:
# -*-coding:utf-8-*-
import socket
import select
import time
EOL1 = b'\n\n'
EOL2 = b'\n\r\n'
response = b'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
response += b'Content-Type: text/plain\r\nContent-Length: 13\r\n\r\n'
response += b'<html><head><title>title</title></head><body><p>Hello, world!</p></body></html>'
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversocket.bind(('0.0.0.0', 8080))
serversocket.listen(1) # the number of client that connect to server
serversocket.setblocking(0) # set 0 not block other block
serversocket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
epoll = select.epoll()
epoll.register(serversocket.fileno(), select.EPOLLIN)
try:
connections = {}
requests = {}
responses = {}
while True:
events = epoll.poll(1)
for fileno, event in events:
if fileno == serversocket.fileno(): # if request come
connection, address = serversocket.accept() # waiting income connection
connection.setblocking(0) # none block
epoll.register(connection.fileno(), select.EPOLLIN) # register socket read event to epoll
connections[connection.fileno()] = connection # add connection to connections dict
requests[connection.fileno()] = b''
responses[connection.fileno()] = response # write data to responses dict
elif event & select.EPOLLIN: # when data in os's read buffer area
requests[fileno] += connections[fileno].recv(1024) # read data from connections
if EOL1 in requests[fileno] or EOL2 in requests[fileno]: # if http message
print('-' * 40 + '\n' + requests[fileno].decode()[:-2])
responses[fileno] += str(time.time())
epoll.modify(fileno, select.EPOLLOUT) # change file number to epoll out mode
elif event & select.EPOLLOUT: # if out mode
byteswritten = connections[fileno].send(responses[fileno]) # write data to os's write buffer
responses[fileno] = responses[fileno][byteswritten:] # get http response message
if len(responses[fileno]) == 0: # if file sent
epoll.modify(fileno, 0) # change file number to hup mode
connections[fileno].shutdown(socket.SHUT_RDWR) # set socket read and write mode shutdown
elif event & select.EPOLLHUP: # if message sent and file number in epoll is hup
epoll.unregister(fileno) # remove file number from epoll
connections[fileno].close() # close connection
del connections[fileno] # delete connection from connections dict
finally:
epoll.unregister(serversocket.fileno())
epoll.close()
serversocket.close()
但是当我打开网页浏览器并访问“http://localhost:8080/”时,我会得到一些类似<html><head><
的数据,它不是完整的数据,只是我数据的一部分。我的问题是什么项目。
查看更多信息请看这张照片。
答案 0 :(得分:2)
你有&#34;内容长度:13&#34;在您的代码中,因此只显示前13个字符!