了解okhttp的都知道,它提供websocket的使用
宣告okhttp client
建立websocket
request request = new request.builder()
.url(serverurl)
.build();
websocket = client.newwebsocket(request, new websocketlistener()
***省略
接下來分析一下okhttp的websocket
在okhttp中封裝的websocket主要是這幾個類
websocket 介面類,提供realwebsocket實現
websocketprotocol 協議
websocketwriter&websocketreader就是對io流的讀寫
realwebsocket 真實實現websocket的類
realwebsocket
那麼websocket是怎麼連線的?
// 將http流提公升為web套接字流
streamallocation streamallocation = internal.instance.streamallocation(call);
streamallocation.nonewstreams(); // prevent connection pooling!
streams streams = streamallocation.connection().newwebsocketstreams(streamallocation);
//處理websocket資訊
try catch (exception e)
}@override public void onfailure(call call, ioexception e)
});}
初始化輸入輸出流
public void initreaderandwriter(string name, streams streams) throws ioexception
//若佇列非空,則傳送資料
if (!messageandclosequeue.isempty())
}//讀取流
reader = new websocketreader(streams.client, streams.source, this);
}
//迴圈接收資料
public void loopreader() throws ioexception
}
pingrunnable心跳執行緒
private final class pingrunnable implements runnable
@override public void run()
}void writepingframe()
if (failedping != -1)
try catch (ioexception e)
}
傳送資料執行緒迴圈獲取佇列資料,並傳送
this.writerrunnable = new runnable()
} catch (ioexception e) }};
執行傳送執行緒於執行緒池
private void runwriter()
}
出列,並傳送資料
boolean writeoneframe() throws ioexception
//出列,傳送資料
writer = this.writer;
pong = pongqueue.poll();
if (pong == null) else
} else if (messageorclose == null) }}
try else if (messageorclose instanceof message)
} else if (messageorclose instanceof close)
} else
return true;
} finally
}
總結:websocket建立乙個http連線,然後將http流提公升為web套接字流,然後不斷從訊息佇列裡傳送資料,並不斷讀取接收到的資料, OkHttp3原始碼解析
compile com.squareup.okhttp3 okhttp 3.6.0 最新版本 okhttp的最底層是使用socket,而不是urlconnection,它通過platform的class.forname 反射獲得當前runtime使用的socket庫。okhttp3使用場景特點 資料...
OkHttp3原始碼(二) Request
request 是對http請求報文概念的具體實現 請求報文的結構圖 根據結構圖去閱讀原始碼能很好的理解某些屬性的真實意義。我們看一下原始碼。public final class request 返回設定的url 返回設定的方法 get或post public string method 返回所有的...
OkHttp3原始碼(三) Header
由於header類是之前已經分析好的,所以這裡直接拿過來就可以了。之所以之前沒有發布這篇部落格是因為在學習header類之前,首先要明白http首部資訊的相關欄位及內容,關於這個如果還不太了解請參看http首部的字段及相應的取值內容 header類屬性 通過字串資料的方式維護資料,用於實現獲取資料的...