Python: Transfer File

From OnnoWiki
Jump to navigation Jump to search

Server

# server.py

import socket                   # Import socket module

port = 60000                    # Reserve a port for your service.
s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
s.bind((host, port))            # Bind to the port
s.listen(5)                     # Now wait for client connection.

print 'Server listening....'

while True:
    conn, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    data = conn.recv(1024)
    print('Server received', repr(data))

    filename='mytext.txt'
    f = open(filename,'rb')
    l = f.read(1024)
    while (l):
       conn.send(l)
       print('Sent ',repr(l))
       l = f.read(1024)
    f.close()

    print('Done sending')
    conn.send('Thank you for connecting')
    conn.close()

Client

# client.py

import socket                   # Import socket module

s = socket.socket()             # Create a socket object
host = socket.gethostname()     # Get local machine name
port = 60000                    # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!")

with open('received_file', 'wb') as f:
    print 'file opened'
    while True:
        print('receiving data...')
        data = s.recv(1024)
        print('data=%s', (data))
        if not data:
            break
        # write data to a file
        f.write(data)

f.close()
print('Successfully get the file')
s.close()
print('connection closed') 

File mytext.txt

Buat file mytext.txt, isi dengan

percobaan
1
2
3
4
5
6
7
8

Output

Output on a local server:

Got connection from ('127.0.0.1', 46607)
('Server received', "'Hello server!'")
('Sent ', "'percobaan\\n1\\n2\\n3\\n4\\n5\\n6\\n7\\n8\\n\\n'")
Done sending

Output on a local client:

file opened
receiving data...
('data=%s', 'percobaan\n1\n2\n3\n4\n5\n6\n7\n8\n\n')
receiving data...
('data=%s', 'Thank you for connecting')
receiving data...
('data=%s', )
Successfully get the file
connection closed

Referensi


Pranala Menarik