我使用Jetty WebSockets作爲服務器端,Autobahn Android作爲客戶端。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();
}
}
提前感謝真棒人!
添加此行mConnection = null; –
@ Poovizhirajan.N:我不能那樣做mConnection是最終的! – brunettia
好吧,等我等我和你電話聯繫 –