2013-02-17 21 views
-1

這是一個簡單的服務器。當您將瀏覽器類型打開到服務器的地址中時,它會響應狀態碼和請求的html的內容。python socket編程 - 如何使用下面的代碼實現多線程?

#import socket module 
from socket import * 
serverSocket = socket(AF_INET, SOCK_STREAM) 

#Prepare a sever socket 
serverSocket.bind((socket.gethostname(), 4501))#Fill in start 
serverSocket.listen(5)#Fill in end 

while True: 
    #Establish the connection 
    print 'Ready to serve...' 
    connectionSocket, addr = serverSocket.accept()#Accepts a TCP client connection, waiting until connection arrives 
    print 'Required connection', addr 
    try: 

     message = connectionSocket.recv(32)#Fill in start #Fill in end 
     filename = message.split()[1] 
     f = open(filename[1:]) 
     outputdata = f.read()#Fill in start #Fill in end 

     #Send one HTTP header line into socket 
     connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n')#Fill in start 


     #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')#Fill in start 
     #Fill in end 

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

您是否嘗試過使用該代碼的任何問題?如果是這樣,你可以發佈它嗎? – 2013-02-17 17:18:14

回答

0

有很多方法可以做到這一點。這裏有一個使用工作線程池的方法:

import Queue 
import threading 

num_workers = 10 
work_q = Queue.Queue() 

def worker(work_q): 
    while True: 
     connection_socket = work_q.get() 
     if connection_socket is None: 
      break 

     try: 
      message = connectionSocket.recv() 
      filename = message.split()[1] 
      f = open(filename[1:]) 
      outputdata = f.read() 
      connectionSocket.send('HTTP/1.0 200 OK\r\n\r\n') 
      connectionSocket.send(outputdata) 
     except IOError: 
      connectionSocket.send('404 Not Found') 
     finally: 
      connectionSocket.close() 

workers = [] 
for i in range(num_workers): 
    t = threading.Thread(target=worker, args=(work_q,)) 
    t.start() 
    workers.append(t) 

while True: 
    #Establish the connection 
    print 'Ready to serve...' 
    connectionSocket, addr = serverSocket.accept() 
    print 'Required connection', addr 
    work_q.put(connectionSocket) 
+0

非常感謝! – 2013-03-31 14:03:07