mfrazi
10/24/2015 - 9:27 AM

sendfile_server.py

import socket, select, sys, os
 
if __name__ == "__main__":   
    # list to keep track of socket descriptors
    CONNECTION_LIST = []

    # list to keep clint id
    CLIENT_ID = {}
    total_client = 0

    RECV_BUFFER = 1024
    PORT = 5000
     
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # this has no effect, why ?
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(("0.0.0.0", PORT))
    server_socket.listen(10)
 
    # add server socket to the list of readable connections
    CONNECTION_LIST.append(server_socket)
 
    print '  > Server started on port ' + str(PORT)
    print ''

    while 1:
        # Get the list sockets which are ready to be read through select
        read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
        for sock in read_sockets:
            #New connection
            if sock == server_socket:
                # Handle the case in which there is a new connection recieved through server_socket
                client_socket, client_address = server_socket.accept()
                CONNECTION_LIST.append(client_socket)
                CLIENT_ID[client_socket] = total_client + 1
                total_client += 1
                print '\n  > Client-%s' % str(CLIENT_ID[client_socket]),
                print '(%s, %s) is connected' % client_address

            #Some incoming message from a client
            else:
                # Data recieved from client, process it
                try:
                    #In Windows, sometimes when a TCP program closes abruptly,
                    # a "Connection reset by peer" exception will be thrown
                    data = sock.recv(RECV_BUFFER)

                    # get command from client 
                    protocol = data.partition(" ")               
                    print '\n  >> Client-%s' % str(CLIENT_ID[sock]), 
                    print '(%s, %s) says: ' % client_address,
                    print data

                    # check first command from client
                    if protocol[0]=='unduh' and len(protocol[1])==1 and len(protocol[2])!=0 :
                        # get full path of file
                        local = os.getcwd()
                        file_name = 'dataset/'+protocol[2]
                        file_path = os.path.join(local,file_name)

                        # check file if exist or not
                        if os.path.exists(file_path):
                            # get file size
                            size = os.path.getsize(file_path)
                            
                            # create message header
                            buf = 'client_id: klien-'
                            buf += str(CLIENT_ID[sock])
                            buf += '\nfile_size: '
                            buf += str(size)
                            buf += '\n\n\n'

                            size += len(buf)

                            # open file in binary mode 
                            file_data = open(file_path,'rb')
                            
                            print '   > Read file : ',
                            # read file
                            sentfile = file_data.read(RECV_BUFFER)
                            buf += sentfile
                            while len(buf) < size:
                                print '......',
                                sentfile = file_data.read(RECV_BUFFER)
                                buf += sentfile
                            print ''

                            # send file to client
                            print '   > Sending file %s' % file_name
                            sock.send(buf)

                            # close file
                            file_data.close()
                            print '   > Finished sending file'
                        else:
                            print '   > File not found'
                            sock.send('File not found')
                    else:
                        print '   > Command not found'
                        sock.send('Command not found')        
                except:
                    print '  > Clien-%s' % str(CLIENT_ID[sock]), 
                    print '(%s, %s) is offline' % client_address
                    sock.close()
                    del CLIENT_ID[sock]
                    #total_client -= 1
                    CONNECTION_LIST.remove(sock)
                    continue
    server_socket.close()