使用python制作TCP Web服务器

时间:2016-10-23 08:51:48

标签: python tcp server webserver

我创建了一个多线程python Web服务器,它对我的​​客户端服务器工作正常。但是我希望它也能为Web服务器提供结果。请帮助我了解我们是如何做到的

服务器

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):
    fileName=sock.recv(1024)
    fileName_string = bytestoString(fileName)
    print(fileName_string)
    stringLength=len(fileName)
    fileName_string = bytestoString(fileName[4:(stringLength-8)])


    if os.path.isfile(fileName_string):
        fileSize=str(os.path.getsize(fileName_string))
        fileSize_Bytes = stringToBytes(fileSize)
        exists_Bytes=stringToBytes('HTTP/1.1 200 OK')
        sock.send(exists_Bytes)
        ContentLength_Bytes=stringToBytes('Content-Length:')
        sock.send(ContentLength_Bytes+fileSize_Bytes)
        userResponse=sock.recv(1024)
        userResponse=bytestoString(userResponse)
        if userResponse[:2]=='Y':
            print ('Ready to send the file................')
            with open(fileName_string,'rb') as fileRead:
                data= fileRead.read(1024)
                sock.send(data)
                while data!="":

                    data=fileRead.read(1024)
                    sock.send(data)
            fileRead.close()
            print('xyz')

        elif userResponse[:2]=='N':
            print('User Terminated file download, Thanks for connecting')

    else :
        httpResponse=stringToBytes('HTTP/1.1 404 not Found')
        sock.send(httpResponse)  

    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)

客户

import sys
import socket

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

#to conver string into bytes
def stringToBytes(bytesToSend):
        bytesToSend= str.encode(bytesToSend)
        type (bytes)
        return(bytesToSend)

#def header():

def Main(serverName,serverPort,fileName_bytes,fileName):
    print('***Initialising the socket***')
    serverAddress=(serverName,serverPort)

    #create the TCP/IP socket using user inout for server and port

    clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    clientSocket.connect(serverAddress)
    httpFileRequest=('GET/'+fileName+' HTTP/1.0')
    httpFileRequest=stringToBytes(httpFileRequest) 
    #Reading the Hostname,socket family, socket type, protocol for the server 

    connectionDetails= socket.getaddrinfo(serverName,serverPort)
    #printing the values to the screen
    print (connectionDetails)
    #print('Family:',families)
    #print('type:',types)
    #print('protocol:',protocols)



    #Sending the request to recieve the file from the server

    if fileName_bytes!="q":
        clientSocket.send(httpFileRequest)
        serverResponse=clientSocket.recv(1024)
        serverResponse_string = bytestoString(serverResponse)
        print(serverResponse_string)
        fileLength=clientSocket.recv(1024)
        fileLength_string = bytestoString(fileLength)
        print(fileLength_string)
        #checking the server response and downloading the file
        if serverResponse_string[13:15]=='OK':
            fileSize= float(int(fileLength_string[15:17]))
            print(('Size of file you wish to download is:'),fileSize)
            clientChoice=input('Please Enter Your Choice (Y/N)?:')
            if clientChoice=='Y':
                clientChoice=stringToBytes(clientChoice)
                clientSocket.send(clientChoice)

                #recieveing the file from the server

                file = open('new_'+fileName,'wb')
                print ('file opened.............')
                data=clientSocket.recv(1024)
                totalRecv=float(len(data))
                file.write(data)
                while totalRecv<fileSize:
                    data=clientSocket.recv(1024)
                    totalRecv+=len(data)
                    file.write(data)
                    percentComplte=int(int((totalRecv)/int(fileSize)*100))
                    print (('we have completed'),percentComplte,('%'))
                file.close()
                print ('Download complete')
            elif clientChoice=='N':
                clientChoice=stringToBytes(clientChoice)
                clientSocket.send(clientChoice) 
                print ('File download terminated')
            else :
                print ('Please enter the correct choice')
        else: 
            print (serverResponse_string)

    clientSocket.close()
    #Getting Hostname,socket family, socket type, protocol for the server 
def get_constants(prefix):
    """Create a dictionary mapping socket module constants to their names."""
    return dict( (getattr(socket, n), n)
                 for n in dir(socket)
                 if n.startswith(prefix)
                 )

#calling main function 
if __name__ == '__main__':
    #getting server hostname and port number from the user
    serverName=sys.argv[1]
    serverPort=int(sys.argv[2])
    fileName= str(sys.argv[3])
    fileName_bytes = str.encode(fileName)
    type(bytes)
    Main(serverName,serverPort,fileName_bytes,fileName)

0 个答案:

没有答案