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的原創文章,請關注公衆號"汪子熙":

相關文章
相關標籤/搜索