Sockets
Sockets
1. Introduction to Sockets
2. Types of Sockets
3. Real-World Applications
1
4. Setting Up a Simple Server and Client
● Server:
○ Listens for incoming connections on a specific port.
Example:
nc -l -p 12345
● Client:
○ Connects to a server’s IP and port.
Example:
nc 127.0.0.1 12345
● Single Connection:
○ A single client connects to a server.
● Multiple Sequential Connections:
○ A single client reconnects multiple times while the server remains active.
● Concurrent Connections:
○ Multiple clients connect to the same server simultaneously.
Client:
#!/bin/bash
nc 127.0.0.1 12345 < file_to_send.txt
Server:
#!/bin/bash
nc -l -p 12345 > received_file.txt
Client:
#!/bin/bash
echo $(date) | nc 127.0.0.1 12345
Server:
#!/bin/bash
nc -l -p 12345
2
7. Sockets vs. REST
● Sockets:
○ Used for low-latency, real-time communication.
○ Protocol: TCP/UDP.
○ Suitable for chat applications, gaming, and live streams.
● REST:
○ Used for structured data exchange over HTTP/HTTPS.
○ Protocol: JSON or XML.
○ Ideal for APIs and web services.
● Encrypted Sockets:
3
Problems with Solutions
Problem 1: Echo Server: Write a server that echoes back any message it receives.
Server:
nc -l -p 12345
Client:
echo "Hello, Server!" | nc 127.0.0.1 12345
Problem 4: Send System Info Client sends the current date and time to the server.
Client:
echo $(date) | nc 127.0.0.1 12345
Server:
nc -l -p 12345