# 171. Using socket for Networking

**Snippet 1: Basic TCP Server**

```python
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 65432))
server.listen()

print("Server is listening...")
conn, addr = server.accept()
print(f"Connected by {addr}")
data = conn.recv(1024)
print(f"Received: {data.decode()}")
conn.sendall(b"Hello from server")
conn.close()
```

***

**Snippet 2: Basic TCP Client**

```python
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 65432))
client.sendall(b"Hello from client")
data = client.recv(1024)
print(f"Received: {data.decode()}")
client.close()
```

***

**Snippet 3: UDP Server**

```python
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(("127.0.0.1", 65432))

print("UDP Server is ready...")
while True:
    data, addr = server.recvfrom(1024)
    print(f"Received {data.decode()} from {addr}")
    server.sendto(b"Hello from server", addr)
```

***

**Snippet 4: UDP Client**

```python
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello from client", ("127.0.0.1", 65432))
data, server = client.recvfrom(1024)
print(f"Received: {data.decode()}")
client.close()
```

***

**Snippet 5: File Transfer Server**

```python
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 65432))
server.listen()

print("Server ready for file transfer...")
conn, addr = server.accept()
with open("received_file.txt", "wb") as file:
    while True:
        data = conn.recv(1024)
        if not data:
            break
        file.write(data)
conn.close()
print("File received successfully.")
```

***

**Snippet 6: File Transfer Client**

```python
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 65432))

with open("file_to_send.txt", "rb") as file:
    data = file.read(1024)
    while data:
        client.send(data)
        data = file.read(1024)

print("File sent successfully.")
client.close()
```

***

**Snippet 7: Multithreaded Chat Server**

```python
import socket
import threading

def handle_client(conn, addr):
    print(f"Connected to {addr}")
    while True:
        msg = conn.recv(1024)
        if not msg:
            break
        print(f"{addr} says: {msg.decode()}")
        conn.sendall(b"Message received")
    conn.close()

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 65432))
server.listen()

print("Chat server is running...")
while True:
    conn, addr = server.accept()
    threading.Thread(target=handle_client, args=(conn, addr)).start()
```

***

**Snippet 8: Multithreaded Chat Client**

```python
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("127.0.0.1", 65432))

while True:
    msg = input("You: ")
    client.sendall(msg.encode())
    data = client.recv(1024)
    print(f"Server: {data.decode()}")
```

***

**Snippet 9: HTTP Server**

```python
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("127.0.0.1", 8080))
server.listen()

print("HTTP Server running...")
while True:
    conn, addr = server.accept()
    request = conn.recv(1024).decode()
    print(f"Request:\n{request}")
    response = "HTTP/1.1 200 OK\n\nHello, HTTP!"
    conn.sendall(response.encode())
    conn.close()
```

***

**Snippet 10: Socket Timeout Example**

```python
import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.settimeout(5)  # Set timeout to 5 seconds

try:
    client.connect(("127.0.0.1", 65432))
    client.sendall(b"Testing timeout")
    data = client.recv(1024)
    print(f"Received: {data.decode()}")
except socket.timeout:
    print("Connection timed out!")
finally:
    client.close()
```

***
