You are here
Home > HelloWorld >

Socket programming in Python

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while other socket reaches out to the other to form a connection. Server forms the listener socket while client reaches out to the server.

Server Socket Methods

1 s.bind()

This method binds address (host name, port number pair) to socket.

2 s.listen()

This method sets up and start TCP listener.

3 s.accept()

This passively accept TCP client connection, waiting until connection arrives .

Client Socket Methods

s.connect()

This method actively initiates TCP server connection.

General Socket Methods

1 s.recv()

This method receives TCP message

2 s.send()

This method transmits TCP message

3 s.recvfrom()

This method receives UDP message

4 s.sendto()

This method transmits UDP message

5 s.close()

This method closes socket

6 socket.gethostname()

Returns the hostname.

A Simple Server program

import socket 
s=socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
while True:
c,addr = s.accept()
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close()

A Simple Client Program

import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.connect((host, port))
print s.recv(1024)
s.close()


This would produce following result :-



Leave a Reply

Top
%d bloggers like this: