做的简单的一个静态web服务器,遇到个bug, 提示osError,这点一不小心就错了,特地记下来,加深记忆,socket须先绑定,再listen,如果是先listen再绑定,系统会自动分配一个端口,而程序绑定不了

 

代码改正之前,先执行了listen,到了bind就报错;此程序只需将listen和改到bind后面即可

from socket import *
from multiprocessing import Process

import re

HTML_FILE = './html'

class Server(object):
     def __init__(self):
          self.server_socket = socket(AF_INET,SOCK_STREAM)
          self.server_socket.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
          self.server_socket.listen(128)

     def bind_addr(self,port):
          self.server_socket.bind(('',port))

     def start(self):

改:将listen放在这里

     self.server-socket.listen(128)
          while True:
              client_socket,client_addr = self.server_socket.accept()
              client_p = Process(target=self.clientDeal,args=(client_socket,))
              client_p.start()
              client_socket.close()

     def clientDeal(self,client_socket):
         recv_data = client_socket.recv(2048)
         requestHeaderLines = recv_data.decode('utf-8').splitlines()
         for line in requestHeaderLines:
        print(line)

        request_start_line = requestHeaderLines[0]
        print(request_start_line)
        file_name = re.match(r'\w+ +(/[^ ]*)',request_start_line).group(1)
        print(file_name)

       if file_name == '/':
           file_name = HTML_FILE + '/index.html'
       else:
           file_name = HTML_FILE + file_name

       try:
           txt = open(file_name,'rb')
       except IOError:
           responseHeaderlines = 'HTTP/1.1 404 NOT Found\r\n'
           response2 = 'server:my server\r\n' + '\r\n'
           responseBody = 'The file is not found!'
      else:
          file_data = txt.read()
          responseHeaderlines = 'HTTP/1.1 200 ok\r\n'
          response2 = 'server:my server\r\n' + '\r\n'
          responseBody = file_data.decode('utf-8')
          txt.close()

     response = responseHeaderlines + response2 + responseBody
     #client_socket.send(bytes(response,'utf-8'))
     client_socket.send(response.encode('utf-8'))
     client_socket.close()

def main():
    server = Server()
    server.bind_addr(999)
    server.start()


if __name__ == '__main__':
    main()

posted @ 2017-08-10 17:36  py小蟒蛇  阅读(289)  评论(0编辑  收藏  举报