top

Search

Python Tutorial

Python's standard library consists of various built-in modules that support interprocess communication and networking. The network access is available at two levels. The 'socket' module defines how server and client machines can communicate at hardware level using socket endpoints on top of the operating system. The 'socket' API supports both connection-oriented and connectionless network protocols. The higher level support is available in Python libraries such as ftplib and httplib, implementing Application level network protocols FTP and HTTP respectively. This chapter takes a look at the functionality of 'socket' module that provides access to BSD socket interface.SocketSockets are the most popular form of inter process communication especially for cross-platform communication. They were invented in Berkeley as part of the BSD Unix. The combination of sockets with INET makes communication between machines very easy.Socket is essentially an end-point of a two-way communication link. It is identified by IP address and the port number. The sockets should be properly configured at both ends so that it initiates a connection, makes it possible to listen for incoming messages and then send the responses at either ends of a client-server environment.The socket() function in 'socket' module sets up a socket object.import socket obj=socket.socket(family, type, protocol)The 'family' argument is AF_INET by default. Other values acceptable are: AF_INET6, AF_UNIX, AF_CAN or AF_RDS.The 'type' argument is by default 'SOCK_STREAM' indicating connection-oriented protocol (TCP) or 'SOCK_DGRAM' representing connection-less protocol(UDP)The 'protocol' argument is usually set to 0 by default.Server Socket methods:The socket instantiated on server is called server socket. Following methods are available to the socket object on server:bind(): This method binds the socket to specified IP address and port number.listen():This method starts server and runs into a listen loop looking for connection request from client.accept():When connection request is intercepted by server, this method accepts it and identifies the client socket with its address.Typical server side code would be:import socket server = socket.socket() server.bind(('localhost',12345)) mySocket.listen() client, addr = mySocket.accept() print ("connection request from: " + str(addr))By default, the server is bound to local machine's IP address 'localhost' listening at arbitrary empty port number.Client socket methods:Similar socket is set up on the client end. It mainly send connection request to server socket listening at its IP address and port numberconnect() :obj=socket.socket() obj.connect((host,port))This method takes a two-item tuple object as argument. The two items are IP address and port number of the server.Once connection is accepted by the server, both the socket objects can send and/or receive data.send():The server sends data to client by using the address it has intercepted.client.send(bytes)Client socket sends data to socket it has established connection with.obj.send(bytes)sendall():similar to send(). However, unlike send(),this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success.sendto():This method is to be used in case of UDP protocol only.recv():This method is used to retrieve data sent to the client. In case of server, it uses the remote socket whose request has been accepted.client.recv(bytes)In case of client,obj.recv(bytes)recvfrom():This method is used in case of UDP protocol.Server code:import socket host = "127.0.0.1" port = 5001 server = socket.socket() server.bind((host,port))         server.listen() conn, addr = server.accept() print ("Connection from: " + str(addr)) while True:        data = conn.recv(1024).decode()        if not data:            break        print ("from connected  user: " + str(data))                                                    data = str(data).upper()        print ("Received from User: " + str(data))        data = input("type message: ")        conn.send(data.encode())                                         conn.close()     Client code:import socket host = '127.0.0.1' port = 5001 obj = socket.socket() obj.connect((host,port)) message = input("type message: ") while message != 'q':        obj.send(message.encode())        data = obj.recv(1024).decode()        print ('Received from server: ' + data)        message = input("type message: ") obj.close()Open two command prompt windows. In one run the server code first. The in other run client code.
logo

Python Tutorial

Python - Socket Module

Python's standard library consists of various built-in modules that support interprocess communication and networking. The network access is available at two levels. The 'socket' module defines how server and client machines can communicate at hardware level using socket endpoints on top of the operating system. The 'socket' API supports both connection-oriented and connectionless network protocols. The higher level support is available in Python libraries such as ftplib and httplib, implementing Application level network protocols FTP and HTTP respectively. This chapter takes a look at the functionality of 'socket' module that provides access to BSD socket interface.

Socket

Sockets are the most popular form of inter process communication especially for cross-platform communication. They were invented in Berkeley as part of the BSD Unix. The combination of sockets with INET makes communication between machines very easy.

Socket is essentially an end-point of a two-way communication link. It is identified by IP address and the port number. The sockets should be properly configured at both ends so that it initiates a connection, makes it possible to listen for incoming messages and then send the responses at either ends of a client-server environment.

The socket() function in 'socket' module sets up a socket object.

import socket
obj=socket.socket(family, type, protocol)

The 'family' argument is AF_INET by default. Other values acceptable are: AF_INET6, AF_UNIX, AF_CAN or AF_RDS.

The 'type' argument is by default 'SOCK_STREAM' indicating connection-oriented protocol (TCP) or 'SOCK_DGRAM' representing connection-less protocol(UDP)

The 'protocol' argument is usually set to 0 by default.

Server Socket methods:

The socket instantiated on server is called server socket. Following methods are available to the socket object on server:

bind(): 

This method binds the socket to specified IP address and port number.

listen():

This method starts server and runs into a listen loop looking for connection request from client.

accept():

When connection request is intercepted by server, this method accepts it and identifies the client socket with its address.

Typical server side code would be:

import socket
server = socket.socket()
server.bind(('localhost',12345))
mySocket.listen()
client, addr = mySocket.accept()
print ("connection request from: " + str(addr))

By default, the server is bound to local machine's IP address 'localhost' listening at arbitrary empty port number.

Client socket methods:

Similar socket is set up on the client end. It mainly send connection request to server socket listening at its IP address and port number

connect() :

obj=socket.socket()
obj.connect((host,port))

This method takes a two-item tuple object as argument. The two items are IP address and port number of the server.

Once connection is accepted by the server, both the socket objects can send and/or receive data.

send():

The server sends data to client by using the address it has intercepted.

client.send(bytes)

Client socket sends data to socket it has established connection with.

obj.send(bytes)

sendall():

similar to send(). However, unlike send(),this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success.

sendto():

This method is to be used in case of UDP protocol only.

recv():

This method is used to retrieve data sent to the client. In case of server, it uses the remote socket whose request has been accepted.

client.recv(bytes)

In case of client,

obj.recv(bytes)

recvfrom():

This method is used in case of UDP protocol.

Server code:

import socket
host = "127.0.0.1"
port = 5001
server = socket.socket()
server.bind((host,port))        
server.listen()
conn, addr = server.accept()
print ("Connection from: " + str(addr))
while True:
       data = conn.recv(1024).decode()
       if not data:
           break
       print ("from connected  user: " + str(data))                                            
       data = str(data).upper()
       print ("Received from User: " + str(data))
       data = input("type message: ")
       conn.send(data.encode())                                        
conn.close()     

Client code:

import socket
host = '127.0.0.1'
port = 5001
obj = socket.socket()
obj.connect((host,port))
message = input("type message: ")
while message != 'q':
       obj.send(message.encode())
       data = obj.recv(1024).decode()
       print ('Received from server: ' + data)
       message = input("type message: ")
obj.close()

Open two command prompt windows. In one run the server code first. The in other run client code.

Python - Socket ModulePython - Socket Module

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Eula

This is my first time here. I am truly impressed to read all this in one place.

Jaypee Dela Cruz

Thank you for your wonderful codes and website, you helped me a lot especially in this socket module. Thank you again!

lucky verma

Thank you for taking the time to share your knowledge about using python to find the path! Your insight and guidance is greatly appreciated.

Pre Engineered Metal Building

Usually I by no means touch upon blogs however your article is so convincing that I by no means prevent myself to mention it here.

Pre Engineered Metal Building

Usually, I never touch upon blogs; however, your article is so convincing that I could not prevent myself from mentioning how nice it is written.

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses the .Net Framework. It utilizes the Common Language Interface (CLI) that describes the executable code as well as the runtime environment. C# can be used for various applications such as web applications, distributed applications, database applications, window applications etc.For greater understanding of this tutorial, a basic knowledge of object-oriented languages such as C++, Java etc. would be beneficial.
C# Tutorial

C# is an object-oriented programming developed by Microsoft that uses ...

Read More