Advertisement
MeKLiN2

python socket

Mar 17th, 2024
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. import socket
  2.  
  3. HOST = '0.0.0.0' # Listen on all network interfaces
  4. PORT = 12345 # Port to listen on
  5.  
  6. def main():
  7. # Create a TCP/IP socket
  8. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
  9. # Bind the socket to the address and port
  10. server_socket.bind((HOST, PORT))
  11.  
  12. # Listen for incoming connections
  13. server_socket.listen()
  14.  
  15. print(f'Server listening on {HOST}:{PORT}')
  16.  
  17. while True:
  18. # Accept incoming connection
  19. client_socket, client_address = server_socket.accept()
  20. print(f'Connection from {client_address}')
  21.  
  22. # Handle the connection
  23. handle_client(client_socket)
  24.  
  25. def handle_client(client_socket):
  26. # Example: Send a simple response
  27. response = b'Hello from the server!\n'
  28. client_socket.sendall(response)
  29. client_socket.close()
  30.  
  31. if __name__ == '__main__':
  32. main()
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement