python中的TCP多线程Web服务器

时间:2016-10-23 18:33:52

标签: python multithreading tcp

我已经创建了一个TCP多线程网络服务器,但它给了我以下内容 如果找到该文件 它说“int obj没有属性编码” 2.稍后,它将显示列表索引超出范围

如果找不到该文件 1.它不会在Web浏览器上显示html错误消息 2.稍后,它将显示列表索引超出范围

我的服务器代码是

import socket
import threading
import os
import sys

#to convert bytes into string 
def bytestoString(stringToRead):
        stringToRead = bytes.decode(stringToRead)
        type(stringToRead)
        return(stringToRead)

#to conver string into bytes
def stringToBytes(bytesToSend1):
        bytesToSend1= str.encode(bytesToSend1)
        type (bytes)
        return(bytesToSend1)
#to retreive a file
def retrFile(name,sock):
    message=sock.recv(1024)
    message_string = bytestoString(message)
    print(message_string)
    fileName=message_string.split()[1]
    fileName=fileName.split("/")[1]
    #stringLength=len(fileName)
    print(fileName)

    if os.path.isfile(fileName):
        print ('Ready to send the file................')
        with open(fileName,'rb') as fileRead:
            data= fileRead.read()
            print (data)
            exists_Bytes=stringToBytes('HTTP/1.1 200 OK\nContent-type=text/html')
            sock.send(exists_Bytes)
            for i in range(0 ,len(data)): 
                sock.send((data[i]).encode())
            print('file sent succesfully')
            sock.close()
    else :
        httpResponse=stringToBytes('HTTP/1.1 404 not Found')
        sock.send(httpResponse)
        #errorDisplayPage=stringToBytes('<html><title>404 Error</title><body>404 Error- Page cannot be found </body></html>')
        sock.send(b'<html><title>404 Error</title><body>404 Error- Page cannot be found </body></html>')
        print ('error message displayed')  
        sock.close()


def Main(serverPort):
    #creating a server socket type TCP
    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    localHost=socket.gethostname()
    #binding the server to the client
    serverSocket.bind((localHost,serverPort))

    serverSocket.listen(5)

    print ('***Server is ready to recieve***')

    while True:

        connectionSocket, addr = serverSocket.accept()
        print ('got connection from:<', addr,'>')
        t=threading.Thread(target=retrFile,args=('retrThread',connectionSocket))
        t.start()
    connectionSocket.send('thank you for connecting')
    connectionSocket.close()


if __name__ == '__main__':
    #getting server hostname and port number from the user
    serverPort=int(sys.argv[1])
    Main(serverPort)

1 个答案:

答案 0 :(得分:0)

您已在代码中以二进制文件的形式打开文件:

with open(fileName,'rb') as fileRead:
    data= fileRead.read()

但是,稍后你会尝试做一些有趣的事情。现在,这在Python 2和3中有所不同。您使用的是Python 3,因此以下块存在问题:

for i in range(0 ,len(data)): 
    sock.send((data[i]).encode())

在python 2中,你会遍历各个字符,它会正常工作。但是,在python 3中,您正在迭代bytes对象,因此data[i]将是int对象。

相反,你可以:

sock.sendall(data)

同样根据wikipedia,HTTP协议假定状态行后跟一个空行。这就是为什么你没有看到错误信息,也看不到文件。

因此,请使用"\n\n"对您的状态代码进行后缀,例如:'HTTP/1.1 404 not Found\n\n'。 OK消息也是如此。

相关问题