Chapter 10 Exercise Set 0: Chapter Review

Sockets For Two-Way Chat

The goal of this exercise is to Modify the example socket code to create a single program that can both send and receive messages. To achieve this, you will need to make several modifications.

  1. First, modify the socket_client program so that it allows the user to type the message at the command line. Your new program should have a while True loop, just like the server program. Inside the loop, it should use input() to receive messages from the command prompt.

  2. Next, combine the socket_client and socket_server programs into a single program that sends and receives messages. Your goal will be to run the same program twice on your computer so that you can chat with yourself. Here are a few things to think about if you want to make this work:

    • This program will work as both a client and a server. Each server needs its own port, so the program will need to know its own port number and the port number of the program it’s communicating with. Use input() to ask for both of these port numbers when the program starts. You can use 5005 and 5006 for the two port numbers.

    • While your program is waiting for you to type a message, it cannot also be listening to receive a message. To handle this constraint, we’ll have the two programs take turns - when one program is sending the other is listening. Come up with a strategy to keep track of which program is sending and which is listening.

    Note

    Real chat applications do not require chatters to take turns, they can both send and listen at the same time using Threads, which are not covered in this text.

API Requests with Python

There are many open APIs and open data sets available. The OpenAPI Initiative and Free APIs two places to look for some of these.

The following program grabs weather information for Arlington, Virginia from a publicly available weather server:

import requests

# Free weather API (no key required for limited use)
url = "https://api.open-meteo.com/v1/forecast"

# Parameters for the request
params = {
    "latitude": 38.88,  # Arlington Virginia coordinates
    "longitude": -77.10,
    "current_weather": True,
    "temperature_unit": "fahrenheit"
}

try:
    # Make the GET request
    response = requests.get(url, params=params)

    # Check if request was successful
    if response.status_code == 200:
        # Parse JSON response
        data = response.json()

        # Extract specific data
        current_weather = data["current_weather"]

        print("🌤️ Weather Information for Arlington Virginia:")
        print("-" * 40)
        print(f"Temperature: {current_weather['temperature']}°F")
        print(f"Wind Speed: {current_weather['windspeed']} mph")
        print(f"Wind Direction: {current_weather['winddirection']}°")

        # Show full response structure (for learning)
        print("\n📊 Full Response Structure:")
        print("-" * 40)
        for key in data.keys():
            print(f"{key}: {type(data[key])}")

    else:
        print(f"Error: Received status code {response.status_code}")

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except KeyError as e:
    print(f"Error parsing data: Missing key {e}")
  1. Read How to read wind direction. Modify the program above so that it reports wind direction using words instead of degrees.