- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Socket programming In Python
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.
Syntax
my_socket = socket.socket (socket_family, socket_type, protocol=0)
Different methods in Server Socket
my_socket.bind()
This method is used for binding address (hostname, port number pair) to socket.
my_socket.listen()
This method is used for set up and start TCP listener.
my_socket.accept()
This method is used for accepting TCP client connection, waiting until connection arrives (blocking).
Different methods in Client Socket
my_socket.connect()
This method actively initiates TCP server connection.
General Socket Methods
my_socket.recv()
This method receives TCP message
my_socket.send()
This method transmits TCP message
my_socket.recvfrom()
This method receives UDP message
my_socket.sendto()
This method transmits UDP message
my_socket.close()
This method closes socket
my_socket.gethostname()
This method returns the hostname.
Server socket
Example
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
Client socket
Example
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
- Related Articles
- Socket Programming with Multi-threading in Python?
- Socket Programming in C#
- Low-level networking interface in Python (socket)
- PHP Socket context options
- Turtle programming in Python
- Tkinter Programming in Python
- Functional Programming in Python
- Object Oriented Programming in Python?
- Hangman Game in Python Programming
- What are Ball and Socket joints?
- What is Secure Socket Layer (SSL)?
- Command Line Interface Programming in Python?
- Meta programming with Metaclasses in Python
- List of Keywords in Python Programming
- Basic Python Programming Challenges
