我在服务器端使用 Jetty WebSockets,在客户端使用 Autobahn Android。
服务器和客户端之间的简单连接可以正常工作。但是当我尝试处理失去连接时遇到了一些麻烦。
在 Android 上,我拥有的是:
private void connectToServer() {
try {
mConnection.connect(getString(R.string.server_addr), new WebSocketHandler(){
// connection au serveur
@Override
public void onOpen(){
Log.d(TAG, "Connected");
Log.d(TAG, "First connexion, sending MAC @");
Log.d(TAG, "My MAC Addr: "+ macAddr);
mConnection.sendTextMessage(macAddr);
}
// reception d'un message text
@Override
public void onTextMessage(String payload) {
//TODO
}
// fermeture de la connexion
@Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection lost. "+reason);
if(mConnection.isConnected()){
Log.d(TAG, "Still connected, disconnect!");
mConnection.disconnect();
}
if(code<4000){
int totalWaitTime = 0;
int waitTime = 0;
Log.d(TAG, "Should be disconnected");
while(!mConnection.isConnected()){
try {
waitTime= random.nextInt(MAX_TO_WAIT - MIN_TO_WAIT + 1) + MIN_TO_WAIT;
Log.d(TAG, "I'll wait "+waitTime+"ms");
totalWaitTime +=waitTime;
Log.d(TAG, "Waiting for "+totalWaitTime+"ms");
if(totalWaitTime <= HOUR_TO_MS){
Thread.sleep(waitTime);
Log.d(TAG, "Trying to reconnect");
connectToServer();
}else{
throw new InterruptedException("Attempt to connect to the server during 1 hours without success");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
} catch (WebSocketException e) {
Log.e(TAG, "Error on connect: "+e.toString());
Log.d(TAG, "is connected: "+mConnection.isConnected());
if(mConnection.isConnected())
mConnection.disconnect();
connectToServer();
}
}
我总是,总是有同样的错误:
06-26 10:36:07.823: E/wingo.stb.qos.AutoStartService(1842): Error on connect: de.tavendo.autobahn.WebSocketException: already connected
但正如你所看到的,我在 onClose() 中关闭了连接,并且当捕获到 WebSocketException 时。这种方法真的有效吗?还是我做错了?
顺便说一句,mConnection 是最终的。所以也许问题来了?
private final WebSocketConnection mConnection = new WebSocketConnection();
在服务器上,当我连接丢失时,我手动关闭会话:
@OnWebSocketClose
public void onClose(Session session, int closeCode, String closeReason){
try {
System.out.println("connexion closed. Reason: "+closeReason);
pingPongTimer.cancel();
if(session.isOpen())
session.close();
WebSocketsCentralisation.getInstance().leave(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
提前感谢很棒的人!