当前位置: 首页 > 工具软件 > autobahn-java > 使用案例 >

websocket autobahn jar包的用法

杨研
2023-12-01
autobahn-0.5.0.jar 文件的地址:  http://pan.baidu.com/s/1slQYcKP
使用websocket好简单方便,据一天来我们公司的大神说:websocket是封装好的成熟的框架,比socket更安全,用起来方便。在原有websocket的基础上加了一个心跳包的功能。
并且设置了一个链接超时的时间限制。代码还需要不停地优化。
package com.example.administrator.connmanager;
import android.content.Context;
import android.os.Handler;
import android.os.TokenWatcher;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import de.tavendo.autobahn.WebSocketOptions;
/**
* @author
* @version 1.0
* @date 2016/9/8 0008
*/
public class ConnManager {
private WebSocketConnection mWebSocketConnection;
private Timer mTimer;
private TimerTask mTimerTask;
private WebSocketOptions mWebSocketOptions;
private Context mContext;
public static List<String> list=new ArrayList<String>();
String uri=null;
public ConnManager(Context context,String ipadress,int port){
mWebSocketConnection=new WebSocketConnection();
mTimer=new Timer();
this.uri="ws://"+ipadress+":"+port;
mWebSocketOptions=new WebSocketOptions();
setwebsocketoptions();
this.mContext=context;
//心跳包,不停地发送消息给服务器
mTimerTask=new TimerTask() {
@Override
public void run() {
mWebSocketConnection.sendTextMessage("");
Log.i("yuhan", "连接中。。。。。");
}
};
}
//链接服务器端的代码
public void connect(){
try {
mWebSocketConnection.connect(uri, new WebSocketHandler() {
@Override
public void onOpen() {
Log.d("yuhan", "Status: Connected to " + uri);
sendHB();
}
@Override
public void onTextMessage(String payload) {
Log.d("yuhan", "Got echo: " + payload);
if(payload.equals("用户刷新-已收到")) {

    nowdate=System.currentTimeMillis();
}

}
@Override
public void onClose(int code, String reason) {
Log.d("yuhan", "Connection lost."+reason);
}
},mWebSocketOptions);
} catch (WebSocketException e) {
Log.d("yuhan", e.toString());
}
}
//开启心跳包,每一秒发送一次消息,如果返回lost再重连
public void sendHB(){
mTimer.schedule(mTimerTask, 1000, 1000);
//每次发送心跳包,服务器接收到响应就会返回一个值,如果查过5s还没有收到返回值,那么就判定是断网。
if((System.currentTimeMillis()-nowdate)>5000&&nowdate!=0) {
    mWebSocketConnection.disconnect();
    
    mTimer.cancel();
    
    // connect();
    Log.i("yuhan", "" + System.currentTimeMillis() + "nowdate:" + nowdate + mWebSocketConnection.isConnected());
    return;
}

}
public void sendMessage(String data){
mWebSocketConnection.sendTextMessage(data);
}
//调整链接是否超时的时间限制
public void setwebsocketoptions(){
mWebSocketOptions.setSocketConnectTimeout(30000);
mWebSocketOptions.setSocketReceiveTimeout(10000);
}
}

 类似资料: