Friday, 5 September 2014

Python program for socket programming to connect two or more PC to share a text file

#1.Server side code

#!/usr/bin/python

import socket
import os

s=socket.socket()      #socket type object created
host=192.168.1.214    #server address
port=21110        #port reserverd for connection
s.bind((host,port))

s.listen(10)

while True:
    c, addrs= s.accept();
    print'Connection created with machine',addrs
    name=c.recv(100)    #receive file name to be read/shared
    print name,'File requested by User'
    file=open(name,"r")    #open file in read mode
   
while True:
    cha=file.read(65500)    #read data from file upto 65500 bytes
    if not cha:
    break            #reached end of file
   c.sendall(cha)        #send file content to requester
c.close()            #close connection


*********************** ******************************

#2.Client side code

#!usr/bin/python

import socket

s=socket.socket()        #socket object created
host=192.168.1.214
port=21110

s.connect((host,port))        #connect with sserver on port
print'Enter file name to be read'
name=raw_input()        #accept input from user
s.send(name)            #send name of file to server
print s.recv(65500)        #receive data from server and print on screen
s.close()            #close connection with server





#change host number as per your system configuration for ip address
#host should be server machine address

No comments:

Post a Comment