使用第三方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){
//Accept return data
}
}
});
}catch (Exception e){
e.printStackTrace();
}
}
This method calls the default connection settings, 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;
}
If you need to change the timeout, you can add parameters to the connect method and pass in the custom WebSocketOptions class, the code is as follows:
WebSocketOptions mWebSocketOptions = new WebSocketOptions ( );
mWebSocketOptions.setSocketConnectTimeout(5000);
mWebSocketOptions.setSocketReceiveTimeout(1000);
Simple use of Android's webSocket
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326323429&siteId=291194637
Recommended
Ranking