summaryrefslogtreecommitdiff
path: root/python/sockets/server.py
blob: aba4a9a13fcc5926738512c2b986919affad73bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import socket

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

# Define the host and port on which the server will listen
host = '127.0.0.1'
port = 8000

# Bind the socket to the host and port
server_socket.bind((host, port))

# Listen for incoming connections
server_socket.listen()

print("Server listening on {}:{}".format(host, port))

while True:
    # Accept a connection
    client_socket, client_address = server_socket.accept()
    print("Connection established with", client_address)

    while True:
        # Receive data from the client
        data = client_socket.recv(1024)
        if not data:
            # If no data is received, client has closed the connection
            print("Connection closed by", client_address)
            break
        print("Received:", data.decode())

        # Send a response back to the client
        client_socket.sendall("Hello from the server!".encode())

    # Close the client socket
    client_socket.close()

# Close the server socket (this part will never be reached in this loop)
server_socket.close()