Код: Выделить всё
import socket
import threading
# Function to handle reading from the socket
def read_from_socket(sock):
while True:
try:
data = sock.recv(1024)
if not data:
continue
print(f"Received data: {data}")
except socket.error as e:
print(f"Socket error: {e}")
break
print("Read thread exiting")
# Create a socket and connect to a server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('example.com', 80))
print ("connected to socket")
# Start the read thread
read_thread = threading.Thread(target=read_from_socket, args=(sock,))
read_thread.start()
# Close the socket after some time
import time
time.sleep(20)
print ("closing the socket")
sock.close()
print ("closed the socket")
# Join the read thread to wait for its completion
read_thread.join()
print("Main thread exiting")
Подробнее здесь: https://stackoverflow.com/questions/792 ... here-is-no
Мобильная версия