Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.1 kB
1
Indexable
Never
import socket

# Define the IP address and port number
ip_address = '10.72.208.221'
port = 8887

# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server

try:
    # Connect to the server
    client_socket.connect((ip_address, port))

    # Open the file for writing
    with open('data.txt', 'w') as file:

        # Continuously read and write the incoming data
        while True:
            data = client_socket.recv(1024)  # Read up to 1024 bytes of data
            print(data)
            if not data:  # Break the loop if no more data is received
                break
            file.write(data.decode())  # Write the decoded data to the file
            print(data.decode())  # Print the received data to the console

except ConnectionRefusedError:
    print("Connection refused: make sure that there is a server listening on port", port)
except Exception as e:
    print("Error:", e)

finally:
    # Close the file and socket
    client_socket.close()