Wednesday 14 October 2015

Socket prog in Python

SERVER.py

import sys
import socket
if len(sys.argv) != 2:
    print "Server"
    sys.exit()
port = int(sys.argv[1])
sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#returns an object
#AF.INET constants represent the address (and protocol) families used for the first argument to socket().
#SOCK_STREAM  These constants represent the socket types
#sd is the object of socket here
address = ("0.0.0.0", port)# address is just a variable
#Bind the socket to address. The socket must not already be bound
sd.bind(address)
print 'Successfully started the server.'

sd.listen(2)
print "Listening for connections now."
sock, addr = sd.accept()

file_name_len = int(sock.recv(2))
file_name = sock.recv(file_name_len)
print "Receiving " + file_name + " from " + addr[0]
outfile = open(file_name, 'w')
# Read 4096 bytes at a time and write them to
# the file. If an empty string is read, it means
# the end of the file has been reached.
while True:
    data = sock.recv(4096)
    if data != '':
        outfile.write(data)
    else:
        break
outfile.close()
print "Done."



CLIENT.py

import sys
import socket
if len(sys.argv) != 4:
    print "Client"
    sys.exit(0)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = (sys.argv[1], int(sys.argv[2]))
file_name = sys.argv[3]
sock.connect(address)
file_p = open(file_name, 'r')
file_data = file_p.read()
file_name_len = str(len(file_name))
sock.sendall(file_name_len.zfill(2))
sock.sendall(file_name)
sock.sendall(file_data)
print file_name + " successfully sent!"
sock.close()

No comments:

Post a Comment