Wednesday, October 29, 2014

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

Problem Statement:

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

PROGRAM

serverm.py

import socket
import threading


#works for 5 times client trying to connect to it.After 5 clients have accessed it, server stops.
class sc(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        threadlock.acquire()
        ch=client.recv(1111)           #RECEIVE choice entered by client

        if ch=='1':                     #client is writing to the server file, temp.txt
            f=open('temp.txt','a+')
            r=client.recv(4096)
            f.write(r+'\n')
            f.close()
        else:
            f=open('temp.txt','a+')      #sending file data to the client from server file.
            msg=f.read()
            client.send(msg)
            f.close()
        threadlock.release()
threadlock=threading.Lock()
s=socket.socket()
s.bind(('localhost',9998))
s.listen(5)                              #5 is the mac number of connections that can be queued for this process
for i in range (0,5):
    client,client_addr=s.accept()
    s1=sc()
    s1.start()
    s1.join()
client.close()
s.close()


clientm.py

import socket
c=socket.socket()

c.connect(("localhost",9998))
ch=raw_input("Enter choice: 1 Write  2 Read\n")
c.send(ch)
if ch=='1':
    print "Writing to the file...\n"
    msg=raw_input("-->")
    c.send(msg)
else:
    print("file contents are...\n")
    msg=c.recv(4096)
    client_file=open('temp_copy.txt','w+')
    client_file.write(msg+'\n')
    client_file.close()
    print(msg)
c.close()

    

No comments:

Post a Comment

Perform a suitable assignment using Xen Hypervisor or equivalent open source to configure it. Give necessary GUI.

 To install kvm on Fedora:  yum install kvm  yum install virt-manager libvirt libvirt-python python-virtinst  su -c "yum install @v...