there is such a code:
server:
import socket
from threading import Thread
from time import sleep
sock = socket.socket()
sock.bind(('', 1337))
sock.listen(1)
conn, addr = sock.accept()
def func1():
while True:
conn.send("1".encode("utf-8"))
sleep(0.5)
def func2():
while True:
conn.send("2".encode("utf-8"))
sleep(0.5)
t1 = Thread(target=func1)
t1.start()
t2 = Thread(target=func2)
t2.start()
client:
import socket
from threading import Thread
from time import sleep
sock = socket.socket()
sock.connect(('localhost', 1337))
def func1():
while True:
data = sock.recv(1024).decode("utf-8")
if data != "1":
print("the package did not arrive properly")
else:
print("package arrived ok")
def func2():
while True:
data = sock.recv(1024).decode("utf-8")
if data != "2":
print("the package did not arrive properly")
else:
print("package arrived ok")
t1 = Thread(target=func1)
t1.start()
t2 = Thread(target=func2)
t2.start()
you need to make sure that the packet sent by function1 comes to function1, and the packet of function2 comes to function2, but this code does not work correctly, and packets from function1 often end up in function2 and vice versa
source https://stackoverflow.com/questions/73548060/how-to-do-something-like-streams-inside-a-port-python-socket
Comments
Post a Comment