There's more...

With a small change to the previous code, we can create a simple client-server application for file transfer. The server instantiates the socket and waits for the connection instance from the client. Once connected to the server, the client starts the data transfer. 

The data to be transferred, which is in the mytext.txt file, is copied byte by byte and sent to the server through the call to the conn.send function. The server then receives the data and writes it to a second file, received.txt.

The source code for client2.py is as follows:

import socket
s =socket.socket()
host=socket.gethostname()
port=60000
s.connect((host,port))
s.send('HelloServer!'.encode())
with open('received.txt','wb') as f:
print ('file opened')
while True :
print ('receiving data...')
data=s.recv(1024)
if not data:
break
print ('Data=>',data.decode())
f.write(data)
f.close()
print ('Successfully get the file')
s.close()
print ('connection closed')

Here is the source code for client.py:

import socket
port=60000
s =socket.socket()
host=socket.gethostname()
s.bind((host,port))
s.listen(15)
print('Server listening....')
while True :
conn,addr=s.accept()
print ('Got connection from',addr)
data=conn.recv(1024)
print ('Server received',repr(data.decode()))
filename='mytext.txt'
f =open(filename,'rb')
l =f.read(1024)
while True:
conn.send(l)
print ('Sent',repr(l.decode()))
l =f.read(1024)
f.close()
print ('Done sending')
conn.send('->Thank you for connecting'.encode())
conn.close()

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.172.68