4 ms·
UDP is certainly faster than TCP, no question about it, because of different levels of quality of service. However, coding for both is similarly simple, given
by ww520 11y ago
UDP is certainly faster than TCP, no question about it, because of different levels of quality of service. However, coding for both is similarly simple, given the same requirement for short receive-only message. TCP session has nothing to do with the complexity. The complexity comes in how to do process() in parallel.
A receive-only message can be handled in TCP:
server_socket = create_and_listen_on_socket(..., MAXCONN)
while True:
csock = server_sock.accept()
msg = csock.recv()
csock.close()
process(msg)
A UDP loop has similar steps, minus the accept and close. The complexity to use threads or async to run process() is the same for UDP and TCP.
For a normal data volume remote command protocol, the simple TCP loop is more than adequate. Just set a reasonable MAXCONN to queue up client connection requests, which can drop connections if there are too many requests, just like UDP dropping packets.
Edit: I don't believe lock can be avoided in Sonic Pi server when handling concurrent incoming commands, whether it's written in Erlang or not. Sonic Pi I believe has a single audio device, which makes it a shared resource. Concurrent access to a shared resource has to be managed with lock somewhere along the call path. In that case a single thread TCP server is perfectly fine, serving as a lock as well.
- im2w1l 11y agoShouldn't you handle fragmentation? I don't think TCP guarantees that csock.recv() will give you all of the message.
- ww520 11y agoFragmented IP datagram is re-assembled at the IP layer before it is handed up to UDP or TCP layer. If it can't be re-assembled, the datagram is considered lost. UDP is unreliable and has small packet size. The TCP code is emulating that simple requirement. Why expand the requirement? Looping to read fully would block on one connection. One rogue client would hold up the whole server.
- im2w1l 11y agoI looked it up, and it seems that while IP will reassemble packets, there is no 1-1 mapping between send calls and IP packets, when using TCP. You are only guaranteed to get the bytes in the correct order but you have to find the boundaries between messages yourself.
- ww520 11y agoThat's correct. A send call could call with a 1GB buffer and the IP layer would have to break it up into multiple datagram packets. That's the nature of TCP. Again sending large message is expanding the requirement beyond what is capable in UDP, while we were striking to emulate UDP in sending short unreliable message.