Socket Programming in Python

This post is for my classmates who finds it difficult to program in Java (To hell with Java’s unfair ). Python helps you here.

Here is a sample Client-Server program that sends messages bidirectionally.

Server.py

#!/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])

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’

request,clientAddress = sock.accept()
print ‘Request received from: ‘, clientAddress
data = request.recv(1024)
print ‘Received Msg: ‘, data
request.send(‘Server Message’)
request.shutdown(2)
sock.close()

Client.py

#!/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])

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((server,port))
sock.send(‘This is the Message from the Client’)
data = sock.recv(1024)
print ‘Received Message: ‘, data
sock.close()

Execution Tips

python Server.py <hostname> <portnumber> (in a terminal)

python Client.py <hostname> <portnumber> (in another terminal)

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