Navigation

What is Socket Programming? Server Code Client Code Steps to Run the Code Concepts of Socket Programming Key Functions

Socket Programming

1. What is Socket Programming?

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket (node) listens on a particular port, while the other socket reaches out to establish a connection. Once connected, they can exchange messages.


2. Server Code

The server listens for a connection on a specific port and sends a message to the client upon connection.

# Server Code import socket # Setup server server_socket = socket.socket() server_socket.bind(('localhost', 12345)) # Bind to localhost and port 12345 server_socket.listen() # Respond to client client_socket, client_conn = server_socket.accept() print(client_socket) print("Connected to " + str(client_conn)) client_socket.sendall(b'Hi from server') # Teardown client_socket.close() server_socket.close()

Explanation:


3. Client Code

The client connects to the server and receives a message.

# Client Code import socket # Setup client client_socket = socket.socket() server_addr = input("Enter server address: ") # e.g., localhost server_port = int(input("Enter server port: ")) # e.g., 12345 # Connect to server client_socket.connect((server_addr, server_port)) print(client_socket.recv(1024)) # Teardown client_socket.close()

Explanation:


4. Steps to Run the Code

  1. Open two Python IDLE instances (or terminals).
  2. Run the server code in one instance. The server will start listening on port 12345.
  3. Run the client code in the other instance. Provide the server address (localhost) and port (12345).
  4. Observe the interaction: The client receives the message "Hi from server".

5. Concepts of Socket Programming


6. Key Functions in Python Socket Programming