使用第三方jar: autobahn-0.5.0.jar
连接代码如下:
public void connect() {
mWebSocketConnection = new WebSocketConnection();
try {
mWebSocketConnection.connect(Url.URL_WEB_SOCKET, new WebSocketHandler() {
@Override
public void onOpen() {
Log.e(TAP,"onOpen");
isConnect = true;
}
@Override
public void onClose(int code, String reason) {
Log.e(TAP,"onClose");
isConnect = false;
}
@Override
public void onTextMessage(String payload) {
Log.e(TAP,"onTextMessage:"+payload);
if(isConnect){
//接受返回数据
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
此方法调用默认连接设置,WebSocketOptions:
public WebSocketOptions() {
this.mMaxFramePayloadSize = 131072;
this.mMaxMessagePayloadSize = 131072;
this.mReceiveTextMessagesRaw = false;
this.mTcpNoDelay = true;
this.mSocketReceiveTimeout = 200;
this.mSocketConnectTimeout = 6000;
this.mValidateIncomingUtf8 = true;
this.mMaskClientFrames = true;
}
如需更改超时时间,可在connect方法中追加参数,将自定义WebSocketOptions类传入,代码如下:
WebSocketOptions mWebSocketOptions = new WebSocketOptions ();
mWebSocketOptions.setSocketConnectTimeout(5000);
mWebSocketOptions.setSocketReceiveTimeout(1000);