Junior
What is a socket?
sobes.tech AI
Answer from AI
A socket is a programming interface (API) for network communication between processes. It provides an abstraction for working with network protocols such as TCP and UDP, allowing programs to send and receive data over the network.
It represents an endpoint for exchanging information. For example, a web server can accept requests from browsers, and a client application can send data to the server.
Sockets can be of two main types:
- Stream sockets (SOCK_STREAM): Use the TCP protocol, ensuring reliable, ordered delivery of data. Suitable for applications requiring delivery guarantees, such as HTTP or FTP.
- Datagram sockets (SOCK_DGRAM): Use the UDP protocol, do not guarantee delivery or order of packets. Used where speed is important, such as in online gaming or streaming video.
The main steps for working with sockets in a network application (example for TCP):
- Creating a socket: Call
socket()to obtain a socket descriptor. - Binding: Bind the socket to a specific IP address and port on the local machine (for server socket).
- Listening: Put the server socket into listening mode for incoming connections.
- Accepting: Accept an incoming connection from a client, creating a new socket for this connection.
- Connecting: Connect the client to the server via IP address and port (for client socket).
- Sending/Receiving: Exchange data through the established connection.
- Closing: Close the socket after finishing work.
Example of creating a TCP socket in Python:
import socket
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Further operations: bind(), listen(), accept() for server
# or connect() for client, send(), recv(), close()