Socket Programming
Socket Programming
Socket Programming
• Socket programming is used for communication between the
applications.
• Java Socket programming can be connection-oriented or connection-
less.
• The client in socket programming must know two pieces of
information:
• 1. IP Address of Server, and
• 2. Port number.
• Here, we are going to make one-way client and server communication
Socket API Overview
Python’s socket module provides an interface to the Berkeley sockets API. This is the module
that you’ll use in this tutorial.
The primary socket API functions and methods in this module are:
•socket()
•.bind()
•.listen()
•.accept()
•.connect()
•.connect_ex()
•.send()
•.recv()
•.close()
Python provides a convenient and consistent API that maps directly to system calls, their C
counterparts. In the next section, you’ll learn how these are used together.
As part of its standard library, Python also has classes that make using these low-level
socket functions easier.
TCP Sockets
You’re going to create a socket object using socket.socket(), specifying the socket type as
socket.SOCK_STREAM. When you do that, the default protocol that’s used is the
Transmission Control Protocol (TCP). This is a good default and probably what you want.
Why should you use TCP? The Transmission Control Protocol (TCP):
•Is reliable: Packets dropped in the network are detected and retransmitted by the
sender.
•Has in-order data delivery: Data is read by your application in the order it was written
by the sender.
In contrast, User Datagram Protocol (UDP) sockets created with socket.SOCK_DGRAM
aren’t reliable, and data read by the receiver can be out-of-order from the sender’s writes.
Server
• A server has a bind() method which binds it to a specific IP and port
so that it can listen to incoming requests on that IP and port. A server
has a listen() method which puts the server into listening mode. This
allows the server to listen to incoming connections. And last a server
has an accept() and close() method. The accept method initiates a
connection with the client and the close method closes the
connection with the client.
# first of all import the socket library
import socket
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our , case it is 12345 but it can be anything
port = 12345
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
c.close()
break
# Import socket module
import socket
# receive data from the server and decoding to get the string.
print(c.recv(1024).decode())
# close the connection
c.close()