In bidirectional communications channel, sockets are two end points. Sockets can communicate between process on the same machine or on different continents.
Sockets are implemented by the different types of channel-TCP, UDP.
For creating Socket, we need socket module and socket.socket () function.
my_socket = socket.socket (socket_family, socket_type, protocol=0)
Different methods in Server Socket
This method is used for binding address (hostname, port number pair) to socket.
This method is used for set up and start TCP listener.
This method is used for accepting TCP client connection, waiting until connection arrives (blocking).
This method actively initiates TCP server connection.
This method receives TCP message
This method transmits TCP message
This method receives UDP message
This method transmits UDP message
This method closes socket
This method returns the hostname.
import socket my_socket = socket.socket() # Create a socket object my_host = socket.gethostname() my_port = 00000# Store a port for your service. my_socket.bind((my_host, my_port)) my_socket.listen(5) # Now wait for client connection. while True: cl, myaddr = my_socket.accept() # Establish connection with client. print ('Got connection from', myaddr) cl.send('Thank you for connecting') cl.close() # Close the connection
import socket # Import socket module my_socket = socket.socket() # Create a socket object my_host = socket.gethostname() # Get local machine name my_port = 00000# Store a port for your service. my_socket.connect((my_host, my_port)) print (my_socket.recv(1024)) my_socket.close