Monday, 5 September 2022

how to do something like streams inside a port (Python socket)

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()

I 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



from how to do something like streams inside a port (Python socket)

No comments:

Post a Comment