taichi
taichi

Reputation: 683

How can I split, send and combine UDP?

I want to do udp communication using the following code.

This code is a sample, and the msg variable in the actual code is longer than 10,000 bytes.

UDPSend.py

from socket import socket, AF_INET, SOCK_DGRAM

HOST = ''
PORT = 5000
ADDRESS = "127.0.0.1"

s = socket(AF_INET, SOCK_DGRAM)
# s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

count = 0
while True:
    msg = 'print("udp_start")\n'
    msg += 'value='+str(count)+'\n'
    msg += 'if value == 100:\n'
    msg += '    print("value is 100")\n\n'
    s.sendto(msg.encode(), (ADDRESS, PORT))
    count = count + 1 
s.close()

UDPRecieve.py

from socket import socket, AF_INET, SOCK_DGRAM

HOST = ''   
PORT = 5000

s = socket(AF_INET, SOCK_DGRAM)
s.bind((HOST, PORT))

while True:
    msg, address = s.recvfrom(8192)
    exec(msg.decode('utf-8'))

s.close()

https://qiita.com/akakou/items/e9fbcfc0c69cc957152e

I want to send the code and exec.

Also, since the msg variable is too long and may cause problems, I would like to split the msg variable into 1000 to 5000 bytes and send it.

How can I do that?

Upvotes: 0

Views: 1185

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123320

You cannot simply split, transmit and concatenate data in UDP since in UDP packets can be lost, duplicated and reordered during transmission. While you might try to add some (complex) reliability layer on top of UDP the question comes why to use UDP in the first place then instead of TCP. I recommend that you rethink if UDP or the current design you use with UDP is really the right choice for your unknown problem, i.e. focus more on the problem and not on your particular idea of a solution. See also XY problem.

Upvotes: 1

Related Questions