Python Socket: Updated Client Server

This is a modification of the previous one

#!/usr/bin/python
import socket
import sys

if len(sys.argv) < 3:
<tab>print ‘Usage: %s [hostname] [portnumber]’ % sys.argv[0]
<tab> sys.exit(1)

server = sys.argv[1]
port = int(sys.argv[2])
msg = ‘start’

#Setup a standard internet socket. Connects to a server
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((server,port))
while msg != ‘exit’:
<tab> msg = raw_input(‘Enter a Message: ‘)
<tab>sock.send(msg)
<tab>data = sock.recv(1024)
<tab>print ‘Received Message: ‘, data
sock.close()

#!/usr/bin/python
import socket
import sys

if len(sys.argv) < 3:
<tab> print ‘Usage: %s [hostname] [portnumber]’ % sys.argv[0]
<tab>sys.exit(1)

hostname = sys.argv[1]
port = int(sys.argv[2])
msg = ‘start’

#Setup a standard internet socket.
#The sockopt call lets this server use the given port even if
#it was recently used by another server
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind((hostname,port))
sock.listen(1)
print ‘Waiting for a Request’

#Handle a client request
request,clientAddress = sock.accept()
print ‘Request received from: ‘, clientAddress
while msg != ‘exit’:
<tab> data = request.recv(1024)
<tab>print ‘Received Msg: ‘, data
<tab> msg = raw_input(‘Enter a Message: ‘)
<tab>request.send(msg)
request.shutdown(2) #Stop the client from reading or writing anything.
sock.close()

Download Source

Advertisements

Leave a comment

Filed under Linux, Programming, Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s