· 

Code解析client1.py

1.Code

import socket

 

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

mysock.connect(('127.0.0.1', 9000))

cmd = 'GET http://127.0.0.1/romeo.txt HTTP/1.0\r\n\r\n'.encode()

mysock.send(cmd)

 

while True:

    data = mysock.recv(512)

    if len(data) < 1:

        break

    print(data.decode(),end='')

 

mysock.close()

2.ChatGPT

 

Can you tell me what the following code does?

(the code is omitted.)

 

What Does This Code Do?

This Python script is a simple HTTP client that connects to a local server running on 127.0.0.1 (localhost) at port 9000 and requests a file named romeo.txt using an HTTP GET request. The response from the server is then received and printed.


Step-by-Step Breakdown

 

  1. Import the socket module

import socket

  • This module is used for network communication.

     2. Create a socket

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  • AF_INET: Uses IPv4.
  • SOCK_STREAM: Uses TCP (as opposed to UDP).

     3. Connect to the server

 

mysock.connect(('127.0.0.1', 9000))

  • Connects to the server running on localhost (127.0.0.1) at port 9000.

     4. Send an HTTP GET request

 

cmd = 'GET http://127.0.0.1/romeo.txt HTTP/1.0\r\n\r\n'.encode()

mysock.send(cmd)

  • The command 'GET http://127.0.0.1/romeo.txt HTTP/1.0\r\n\r\n' is an HTTP request asking for romeo.txt.
  • The request follows HTTP/1.0, meaning the connection will close after the response is received.
  • \r\n\r\n marks the end of the request headers.
  • .encode() converts the string into bytes, which is required for network transmission.
  • mysock.send(cmd) sends this request to the server.

     5. Receive and display the response

while True:

    data = mysock.recv(512)  # Receive up to 512 bytes at a time

    if len(data) < 1:  # If no data is received, stop the loop

        break

    print(data.decode(), end='')  # Decode bytes to string and print

  • The loop continuously receives data from the server in chunks of 512 bytes.
  • If no data is received (len(data) < 1), it means the server has finished sending, so the loop breaks.
  • data.decode() converts the received bytes into a string, and print(..., end='') ensures the output is continuous.

     6. Close the socket

 

mysock.close()

  • Closes the connection once all data is received.

Expected Output

 

If a web server (like the Python server from your previous questions) is running on localhost:9000 and has romeo.txt, the script might output:

HTTP/1.1 200 OK

Content-Type: text/plain

 

O, she doth teach the torches to burn bright!

It seems she hangs upon the cheek of night

Like a rich jewel in an Ethiope’s ear;


Key Takeaways

  • This script simulates a basic web browser, requesting a file from a local server.

  • It connects via TCP, sends an HTTP GET request, receives data, and prints the response.

  • The response will contain HTTP headers followed by the actual file contents.

 

Would you like to test it with a simple Python server that serves romeo.txt? 😊

 

ChatGPTが、romeo.txtを含むserverを提案しているので、次の章で見ることにします。

 

3.a simple Python server that serves romeo.txt

 

Yes, I would like to test the code with a simple Python server that serves romeo.txt.

 

Step 1: Create a Simple Python Server

Before running your client script, you need a basic Python server to serve romeo.txt.

1.1 Create romeo.txt

 

Save the following text as romeo.txt in the same directory as your script:

O, she doth teach the torches to burn bright!

It seems she hangs upon the cheek of night

Like a rich jewel in an Ethiope’s ear;

1.2 Create simple_server.py

 

Save the following Python script as simple_server.py:

from socket import *

 

def createServer():

    serversocket = socket(AF_INET, SOCK_STREAM)

    try:

        serversocket.bind(('localhost', 9000))  # Bind to port 9000

        serversocket.listen(5)

        print("Server is ready. Access: http://localhost:9000/romeo.txt")

 

        while True:

            clientsocket, address = serversocket.accept()

            request = clientsocket.recv(1024).decode()

            print(request)  # Print the request received

 

            # Check if the request is for romeo.txt

            if "GET /romeo.txt" in request:

                response = "HTTP/1.1 200 OK\r\n"

                response += "Content-Type: text/plain\r\n\r\n"

                with open("romeo.txt", "r") as file:

                    response += file.read()

            else:

                response = "HTTP/1.1 404 Not Found\r\n\r\nFile not found."

 

            clientsocket.sendall(response.encode())

            clientsocket.shutdown(SHUT_WR)

            clientsocket.close()

 

    except KeyboardInterrupt:

        print("\nShutting down server...")

    

    except Exception as e:

        print("Error:", e)

 

    serversocket.close()

 

# Start the server

createServer()

 

Step 2: Run the Server

 

  1. Open a terminal or command prompt.

  2. Run the server script:

python simple_server.py


     3. The server will start and listen on localhost:9000.


Step 3: Run the Client Script

 

Now, run the client script you provided earlier:

(code omitted)

Expected Output (Client Terminal)

 

If everything works correctly, your client should receive and print:

HTTP/1.1 200 OK

Content-Type: text/plain

 

O, she doth teach the torches to burn bright!

It seems she hangs upon the cheek of night

Like a rich jewel in an Ethiope’s ear;

If the file is missing or there’s an issue, you might see:

HTTP/1.1 404 Not Found

 

File not found.


Troubleshooting

  • If the client cannot connect, ensure the server is running before starting the client.

  • If another process is using port 9000, change it in both scripts.

  • If you get an error saying romeo.txt is missing, make sure it exists in the same directory as simple_server.py.

 

Let me know if you run into any issues! 🚀

 

上の手順にしたがって、serverをrunし、clientをrunしたら、client側のterminalにromeo.txtがprint outされました。ただし、serverがCtr-Cを押してもうまくshut downできないので、PIDを調べて、taskkillしました。

 

他の方法として、Ctr-Cを押した後、bwoserでlocalhost:9000を開こうとすると、serverがshut downするようです。

 

4.Execute another code while running a code

そもそもこれが可能かどうか、ChatGPTに聞いてみました。

 

Can I run another Python code while running a Python code on the same PC?

 

Yes, you can run multiple Python scripts simultaneously on the same PC. Here are some ways to do it:

1. Open Multiple Terminal/Command Prompt Windows

  • Open two terminal (or command prompt) windows.

  • Run the first script in one window:

    nginx
    python simple_server.py
  • Open another terminal and run the second script:

    nginx
    python client_script.py

2. Use Background Execution (& or nohup)

  • On Windows, you can start a script in a new process using:

    sql
    start python simple_server.py
  • On Linux/macOS, you can run a script in the background using:

    nginx
    python simple_server.py &

3. Use Multiprocessing in Python

If you want to run multiple scripts within the same Python process, you can use Python’s multiprocessing module to run them in parallel.

 

Would you like a code example for running scripts in parallel using multiprocessing? 🚀

 

2つのcodeを同時にrunするには、異なるterminalでrunさせればよいとのことです。