Use Python for Socket Programming to connect two or more PCs to share a text file.

#At the client side...
import socket
import time
HOST = '10.5.10.16'   # Symbolic name meaning the local host. When connecting two different machines, use the ip address of the host machine.
PORT = 24070 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
print '***** CLIENT IS READY NOW*********';
while True:
    command = raw_input('Enter your filename: ')
   
    fil=open(command,"r")
    buf=fil.read()
    print '************SERVER IS READY***********';
    time.sleep(10);
    print '**** THE CLIENT HAS SUCCESSFULLY DELIVER THE CONTENT OF FILE *****';
    s.send(buf)
   
    reply = s.recv(1024)
    if reply=='Quit':
        break
    print reply





#At the Host Side...
import socket
import sys
 
HOST = '10.5.10.16'   # Symbolic name meaning the local host. When connecting two different machines, use the ip address of the host machine.
PORT = 24070    # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
    s.bind((HOST, PORT))      #bind method
except socket.error , msg:
    print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket bind complete'
s.listen(1)        
print 'Socket now listening'
 
# Accept the connection once (for starter)
(conn, addr) = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
stored_data = ''
while True:
    # RECEIVE DATA
    data = conn.recv(1024)           # receive up to 1K bytes
 
    # PROCESS DATA
   
   
    stored_data = str(data)         # Get the data as second token, save it
    fil=open("newtxtfile","w")
    fil.write(stored_data)
    fil.close()
 
    fil=open("newtxtfile","r")
    print fil.read()
    fil.close()
    reply = 'OK'                      # Acknowledge that we have stored the data
    
    if data=='QUIT':                 # Client is done
        conn.send('Quit')                 # Acknowledge
        break                             # Quit the loop
 
    # SEND REPLY
    conn.send(reply)
conn.close() # When we are out of the loop, we're done, close
 

Comments