TCP socket和web socket的区别

小编先习惯性的看了下某中文百科网站对Web Socket的介绍,以为很囧。若是你们按照这个答案去参加BAT等互联网公司的前端开发面试,估计会被鄙视。前端

仍是让咱们阅读一些英文材料吧。web

让咱们直接看stackoverflow上的原文,而后翻译: 面试

原文地址:less

https://stackoverflow.com/questions/16945345/differences-between-tcp-sockets-and-web-sockets-one-more-timesocket

这个讨论有超过8万的阅读量。 tcp

首先咱们来阅读这段有166个赞的回答: ide

When you send bytes from a buffer with a normal TCP socket, the send function returns the number of bytes of the buffer that were sent. 当咱们向一个一般的TCP套接字发送一段来自内存buffer中的字节数据时,send系统调用返回的是实际发送的字节数。 If it is a non-blocking socket or a non-blocking send then the number of bytes sent may be less than the size of the buffer.函数

若是发送数据的目的方套接字是一个非阻塞套接字或者是对写操做非阻塞的套接字,那么send返回的已发送字节数可能小于buffer中待发送字节数。工具

If it is a blocking socket or blocking send, then the number returned will match the size of the buffer but the call may block. 若是是阻塞套接字,二者会相等,由于顾名思义,若是send系统调用没有把全部待发送数据所有发送,则API调用不会返回。网站

With WebSockets, the data that is passed to the send method is always either sent as a whole "message" or not at all. Also, browser WebSocket implementations do not block on the send call.

而Web socket和TCP socket的区别,从发送的数据来看,再也不是一系列字节,而是按照一个完整的"消息体"发送出去的,这个"消息体"没法进一步再分割,要么所有发送成功,要么压根就不发送,不存在像TCP套接字非阻塞操做那样出现部分发送的状况。换言之,Web Socket里对套接字的操做是非阻塞操做。

这个区别在维基百科上也有清晰阐述: Websocket differs from TCP in that it enables a stream of messages instead of a stream of bytes

再来看接收方的区别。 原文: But there are more important differences on the receiving side of things. When the receiver does a recv (or read) on a TCP socket, there is no guarantee that the number of bytes returned correspond to a single send (or write) on the sender side. It might be the same, it may be less (or zero) and it might even be more (in which case bytes from multiple send/writes are received). With WebSockets, the receipt of a message is event driven (you generally register a message handler routine), and the data in the event is always the entire message that the other side sent.

同理,在TCP套接字的场景下,接收方从TCP套接字读取的字节数,并不必定等于发送方调用send所发送的字节数。而WebSocket呢?WebSocket的接收方从套接字读取数据,根本不是像TCP 套接字那样直接用recv/read来读取, 而是采起事件驱动机制。即应用程序注册一个事件处理函数,当web socket的发送方发送的数据在接收方应用从内核缓冲区拷贝到应用程序层已经处于可用状态时 ,应用程序注册的事件处理函数以回调(callback)的方式被调用。

看个例子:

我经过WebSocket发送一个消息“汪子熙”:

在调试器里看到的这个字符串做为回调函数的输入参数注入到函数体内:

Chrome开发者工具里观察到的WebSocket消息体:

下次面试被面试官问到TCP和WebSocket套接字的区别,相信你们应该可以知道如何回答了。

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

相关文章
相关标签/搜索