0
0
Computer-networksConceptBeginner · 3 min read

What Is a Socket in Networking? Simple Explanation and Example

A socket in networking is an endpoint for sending or receiving data across a network. It acts like a door that programs use to communicate with each other over the internet or local networks.
⚙️

How It Works

A socket works like a phone line between two computers. Imagine you want to call a friend; you pick up your phone and dial their number. Similarly, a socket connects two programs by using an IP address and a port number, which is like the phone number for computers.

When a program opens a socket, it creates a communication channel. One side listens for messages, and the other side sends messages through this channel. This allows data to flow back and forth, enabling things like web browsing, chatting, or file sharing.

💻

Example

This simple Python example shows how a socket can be used to create a server that listens for connections and sends a greeting message.

python
import socket

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to localhost on port 12345
server_socket.bind(('127.0.0.1', 12345))

# Listen for incoming connections
server_socket.listen(1)
print('Server is listening on port 12345...')

# Accept a connection
client_socket, addr = server_socket.accept()
print(f'Connection from {addr}')

# Send a message to the client
client_socket.sendall(b'Hello from server!')

# Close the connection
client_socket.close()
server_socket.close()
Output
Server is listening on port 12345... Connection from ('127.0.0.1', <client_port>)
🎯

When to Use

Sockets are used whenever two programs need to communicate over a network. This includes web servers and browsers, chat applications, online games, and file transfer tools.

Use sockets when you want real-time communication or to send data between devices. They are essential for building networked applications that require direct data exchange.

Key Points

  • A socket is like a communication endpoint between two programs.
  • It uses an IP address and port number to connect.
  • Sockets enable sending and receiving data over networks.
  • They are fundamental for internet communication and networked apps.

Key Takeaways

A socket is an endpoint that allows programs to communicate over a network.
It uses IP addresses and port numbers to establish connections.
Sockets enable real-time data exchange between devices.
They are essential for building networked applications like web servers and chat apps.