summaryrefslogtreecommitdiff
path: root/python/sockets/server.py
diff options
context:
space:
mode:
authorpants <niklasjo2004@gmail.com>2026-09-21 14:17:45 -0700
committerpants <niklasjo2004@gmail.com>2026-09-21 14:17:45 -0700
commita33d49ac4d1ce554c72770927957a089b4023bf1 (patch)
tree17ea036b5a0e8b488dc236f0ce48a275ecd80ef8 /python/sockets/server.py
Diffstat (limited to 'python/sockets/server.py')
-rw-r--r--python/sockets/server.py39
1 files changed, 39 insertions, 0 deletions
diff --git a/python/sockets/server.py b/python/sockets/server.py
new file mode 100644
index 0000000..aba4a9a
--- /dev/null
+++ b/python/sockets/server.py
@@ -0,0 +1,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()