okhttp-ws can send ping/pong on both server and client side
okhttp-ws can only support client send ping and server response pong.
I have a requirment which is server send ping and client send pong.
Hope I can use okhttp-ws....
okHttp-ws actual has implement this feature, but interface is not disclosed. The implementation would be a simple change.
Check this code
public RealWebSocket(boolean isClient, BufferedSource source, BufferedSink sink, Random random,
final Executor replyExecutor, final WebSocketListener listener, final String url) {
this.listener = listener;
writer = new WebSocketWriter(isClient, sink, random);
reader = new WebSocketReader(isClient, source, new FrameCallback() {
@Override public void onMessage(ResponseBody message) throws IOException {
listener.onMessage(message);
}
@Override public void onPing(final Buffer buffer) {
replyExecutor.execute(new NamedRunnable("OkHttp %s WebSocket Pong Reply", url) {
@Override protected void execute() {
try {
writer.writePong(buffer);
} catch (IOException ignored) {
}
}
});
}
@Override public void onPong(Buffer buffer) {
listener.onPong(buffer);
}
@Override public void onClose(final int code, final String reason) {
readerSentClose = true;
replyExecutor.execute(new NamedRunnable("OkHttp %s WebSocket Close Reply", url) {
@Override protected void execute() {
peerClose(code, reason);
}
});
}
});
}
So the feature request is to notify the application layer when a ping occurs?
Yes, I think so.
I think that’s an awkward design. What’s the motivation?
I hope application layer can handle the response data of pong depends on the input from ping data, not just simply return pong taking ping data.
for example: server: ping(A) client: pong(AB)
That would violate section 5.5.3 of RFC 6455 which states:
A Pong frame sent in response to a Ping frame must have identical "Application data" as found in the message body of the Ping frame being replied to.
Yes, you are right. But I still hope application layer would be notified while receiving ping, so we can handle heartbeat by application.
It's unlikely that feature will survive the inevitable websockets on HTTP/2 spec.
I agree the example is a mistake. But the spec does motion application layer should not be noticed on ping.
We have decided not to implement this. From a survey of a large group of web socket APIs, pings and pongs are rarely used and pings never have any bearing on the application layer. This is exacerbated by the fact that JavaScript doesn't expose a way to send pings at all.
We added ping intervals in 3.10.0. https://github.com/square/okhttp/blob/master/CHANGELOG.md#version-3100