作者:倒颠0 | 来源:互联网 | 2023-08-26 15:36
ThisquestionisNOTforthedifferencebetweenSTREAMtypeandDATAGRAMtypeINTERNETsockets.Ikn
This question is NOT for the difference between STREAM type and DATAGRAM type INTERNET sockets. I know that STREAM sockets use TCP, Datagram sockets use UDP and all the TCP,UDP stuff, packets arriving in order, ACK, NACK etc. I understand the importance of these over internet.
这个问题不是关于流类型和数据报类型INTERNET套接字之间的区别。我知道流套接字使用TCP,数据报套接字使用UDP和所有TCP、UDP之类的东西,按顺序到达的包,ACK, NACK等等。我理解这些在internet上的重要性。
Q1) When I create a UNIX domain socket which is a local socket, how would it matter if the socket is STREAM socket or DATAGRAM socket. This type of socket would write the data to the socket file, would the protocol matter in this case since I am not transmitting data over a network? Is there any chance of data loss in this case if I use UNIX-based DATAGRAM sockets?
Q2) Does UNIX DATAGRAM sockets provide better performance than UNIX STREAM sockets?
Q3) How to decide for a STREAM/DATAGRAM UNIX based socket in my application?
当我创建UNIX域套接字(即本地套接字)时,如果套接字是流套接字或数据报套接字,那又有什么关系呢?这种类型的套接字将数据写入套接字文件,在这种情况下,协议是否重要,因为我不通过网络传输数据?在这种情况下,如果我使用基于unix的数据报套接字,是否有可能丢失数据?UNIX数据报套接字是否比UNIX流套接字提供更好的性能?Q3)如何在我的应用程序中确定基于流/数据报UNIX的套接字?
Thanks
谢谢
4 个解决方案
50
Just as the manual page says Unix sockets are always reliable. The difference between SOCK_STREAM
and SOCK_DGRAM
is in the semantics of consuming data out of the socket.
正如手册页所说,Unix套接字总是可靠的。SOCK_STREAM和SOCK_DGRAM之间的区别在于从套接字中使用数据的语义。
Stream socket allows for reading arbitrary number of bytes, but still preserving byte sequence. In other words, a sender might write 4K of data to the socket, and the receiver can consume that data byte by byte. The other way around is true too - sender can write several small messages to the socket that the receiver can consume in one read. Stream socket does not preserve message boundaries.
流套接字允许读取任意数量的字节,但仍然保留字节序列。换句话说,发送方可能向套接字写入4K数据,而接收方可以逐个字节地使用该数据。另一种方法也是正确的——发送方可以向套接字写入几个小消息,接收方可以在一次读取中使用这些消息。流套接字不保留消息边界。
Datagram socket, on the other hand, does preserve these boundaries - one write by the sender always corresponds to one read by the receiver (even if receiver's buffer given to read(2)
or recv(2)
is smaller then that message).
而另一方面,数据报套接字则保留了这些边界——发送方的写入总是对应于接收方的读取(即使接收方给读(2)或recv(2)的缓冲区小于该消息)。
So if your application protocol has small messages with known upper bound on message size you are better off with SOCK_DGRAM
since that's easier to manage.
因此,如果您的应用程序协议具有消息大小已知上限的小消息,那么最好使用SOCK_DGRAM,因为这样更容易管理。
If your protocol calls for arbitrary long message payloads, or is just an unstructured stream (like raw audio or something), then pick SOCK_STREAM
and do the required buffering.
如果您的协议调用任意长的消息有效负载,或者只是一个非结构化的流(如原始音频或其他),那么选择SOCK_STREAM并进行所需的缓冲。
Performance should be the same since both types just go through local in-kernel memory, just the buffer management is different.
性能应该是相同的,因为这两种类型都只经过本地内核内存,只是缓冲区管理不同。