“面向连接”就是在正式通信前必须要与对方建立起连接。比如你给别人打电话,必须等线路接通了、对方拿起话筒才能相互通话。
“面向非连接”就是在正式通信前不必与对方先建立连接,不管对方状态就直接发送。与手机短信、QQ发信息非常相似:你在发短信的时候,只需要输入对方手机号、QQ号就OK了。
TCP(Transmission Control Protocol,传输控制协议)是基于连接的协议,也就是说,在正式收发数据前,必须和对方建立可靠的连接。一个TCP连接必须要经过三次“对话”才能建立起来,其中的过程非常复杂,我们这里只做简单、形象的介绍,你只要做到能够理解这个过程即可。我们来看看这三次对话的简单过程:主机A向主机B发出连接请求数据包:“我想给你发数据,可以吗?”,这是第一次对话;主机B向主机A发送同意连接和要求同步(同步就是两台主机一个在发送,一个在接收,协调工作)的数据包:“可以,你什么时候发?”,这是第二次对话;主机A再发出一个数据包确认主机B的要求同步:“我现在就发,你接着吧!”,这是第三次对话。三次“对话”的目的是使数据包的发送和接收同步,经过三次“对话”之后,主机A才向主机B正式发送数据。
UDP(User Data Protocol,用户数据报协议)是与TCP相对应的协议。它是面向非连接的协议,它不与对方建立连接,而是直接就把数据包发送过去!
备注:基于TCP传输的上层协议为TLS;基于UDP传输的上层协议为DTLS。应用层和网络层之间(即OSI模型中的会话层)
关于TLS与DTLS区别请参看本人博客《TLS与DTLS区别》
实际上DTLS 1.0 基于 TLS 1.1扩展, DTLS 1.2 基于TLS 1.2扩展。
下面表格是二者最典型的差异:
TCP | UDP | |
是否面向连接 | 面向连接 | 非面向连接 |
传输可靠性 | 可靠 | 不可靠 |
数据包 | stream 丢包重传、组合 | packet |
有序 | 顺序 | 无序 |
速度 | 慢 | 快 |
应用 | 大数据 | 小数据 |
支持应用层协议 | HTTP/SMTP/FTP | IPTV/VoIP/TFTP |
下面是英文的相关解释文章,有兴趣可以看下:
Difference between TCP and UDP
TCP | UDP |
Reliability: TCP is connection-oriented protocol. When a file or message send it will get delivered unless connections fails. If connection lost, the server will request the lost part. There is no corruption while transferring a message. | Reliability: UDP is connectionless protocol. When you a send a data or message, you don't know if it'll get there, it could get lost on the way. There may be corruption while transferring a message. |
Ordered: If you send two messages along a connection, one after the other, you know the first message will get there first. You don't have to worry about data arriving in the wrong order. | Ordered: If you send two messages out, you don't know what order they'll arrive in i.e. no ordered |
Heavyweight: - when the low level parts of the TCP "stream" arrive in the wrong order, resend requests have to be sent, and all the out of sequence parts have to be put back together, so requires a bit of work to piece together. | Lightweight: No ordering of messages, no tracking connections, etc. It's just fire and forget! This means it's a lot quicker, and the network card / OS have to do very little work to translate the data back from the packets. |
Streaming: Data is read as a "stream," with nothing distinguishing where one packet ends and another begins. There may be multiple packets per read call. | Datagrams: Packets are sent individually and are guaranteed to be whole if they arrive. One packet per one read call. |
Examples: World Wide Web (Apache TCP port 80), e-mail (SMTP TCP port 25 Postfix MTA), File Transfer Protocol (FTP port 21) and Secure Shell (OpenSSH port 22) etc. | Examples: Domain Name System (DNS UDP port 53), streaming media applications such as IPTV or movies, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP) and online multiplayer games etc |