Python Networking

Python Networking

Python provides several libraries for network programming, such as the socket module, which helps you to work with network connections.

Creating a Simple Server and Client

Here is an example of a simple server and client using Python's socket module:

Server Code:

      
        import socket

        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('localhost', 8080))
        server.listen(5)

        print("Server started, waiting for connection...")

        while True:
            client_socket, client_address = server.accept()
            print(f"Connection from {client_address}")
            client_socket.send("Hello, Client!".encode())
            client_socket.close()
      
    

Client Code:

      
        import socket

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect(('localhost', 8080))

        message = client.recv(1024)
        print(f"Message from server: {message.decode()}")

        client.close()
      
    

Activity

Try It Yourself!

Modify the server to send a custom message to the client, and have the client send a response back to the server.

Quick Quiz

Quick Quiz

  1. What is the main function of the socket module?
  2. How do you establish a connection to a server in Python?

Answers: The socket module is used to work with network connections. You can establish a connection by calling connect() on a client socket object.