Why do stream sockets require net/read and net/write while datagram sockets require net/recv-from and net/send-to? #1441
-
https://janet-lang.org/docs/networking.html offers no explanation of why. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
That's not exactly what it says, but that is more or less conventional. Conceptually, none of this is Janet-specific; it's just how networking works (especially with the BSD sockets API). Stream sockets are always connected to a specific peer, so the source and destination addresses are stored in the stream. Once the connection is established, you can just read and write to the stream, much like a file. Datagram sockets can be bound to an address, but they don't have to be, since each datagram is sent or received independently. In fact, the documentation shows both approaches. On the client side, you're probably only talking to a single server, so it probably makes sense to "connect" to it and read/write. Although this is really just a convenience: you could use send-to/recv-from on the client and specify/verify the server address for every message. On the server side, you're probably interacting with multiple clients, so it probably makes sense to just receive datagrams from any address and send them to any address on a case-by-case basis. Ultimately, it depends on the situation. The client/server distinction might not be clear for all applications, so this is just a starting point. |
Beta Was this translation helpful? Give feedback.
If you're new to networking, Janet's documentation probably isn't the best place to start. I would look for a general tutorial on networking first.
Briefly, a stream socket is like a telephone call: you make a connection, both sides know who they're talking to, and you can just talk back and forth until you're done. Datagrams are more like putting postcards in the mail: you have to put the destination and return address on each one individually. Also, at least in the case of UDP, there's no guarantee that it will arrive.
Most everyday networking, such as https, is all streams. Datagrams are more niche; if you're not sure what they are, you can probably ignore them until later.