您的位置:首页 > 移动开发 > Android开发

android中如何使用websocket,以及用nodejs做后台的实例

2017-02-21 18:47 621 查看
开始前,我们需要一个网上开源的支持websocket的jar库(应该这么说吧…)

这个是jar包,要在libs中导入autobahn-0.5.0.jar , 这是下载地址

现在开始android端service的编写

public class WebSocketService extends Service {

private static final String TAG = WebSocketService.class.getSimpleName();

private static WebSocketConnection webSocketConnection;
private static WebSocketOptions options = new WebSocketOptions();
//websocket地址 这个地址到时候使用nodejs的时候在说(后台也会给的)
public static String WEB_SOCKET_HOST = "ws://"+ ipaddress +":8010/";//后面的是端口号自己定义(后端定义)

//心跳监听(定时给服务器发送信息防止断开连接)
private Timer mTimer;

//贴出主要代码
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

//这里根据网路状态监听 , 来进行开启和关闭
if( isWifi){
webSocketConnect();//打开长连接
}else{
closeWebsocket();//断开长连接
}
}

//开启操作
public void webSocketConnect() {
L.e("开启长链接!!");

webSocketConnection = new WebSocketConnection();
try {
webSocketConnection.connect(WEB_SOCKET_HOST , new WebSocketHandler() {

//websocket启动时候的回调
@Override
public void onOpen() {
Log.e(TAG, "onOpen: 开启成功!!");

mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if (webSocketConnection != null ) {
webSocketConnection.sendTextMessage("xin tiao");
}
}
}, 0, 60 * 1000);
}

//websocket接收到消息后的回调
@Override
public void onTextMessage(String payload) {
L.e(payload + "回调");
//EventBus.getDefault().post(payload );
}

//websocket关闭时候的回调
@Override
public void onClose(int code, String reason) {
Log.e(TAG, "onClose: 服务器关闭!!" + reason);

if (mTimer != null) mTimer.cancel();
//  EventBus.getDefault().post("close");
}
}, options);
} catch (WebSocketException e) {
e.printStackTrace();
}
}
//测试使用,在activity中调用
public static void sendMsg(String s) {
if (!TextUtils.isEmpty(s))
if (webSocketConnection != null) {
webSocketConnection.sendTextMessage(s);
}
}

//关闭操作
public void closeWebsocket() {

if (webSocketConnection != null && webSocketConnection.isConnected()) {
webSocketConnection.disconnect();
webSocketConnection = null;
}
}

@Override
public void onDestroy() {
super.onDestroy();
if (mTimer != null) {
mTimer.cancel();
}

}

}


OK , 上面就是在android端中代码的编写!只需要开启服务就可以了!然后就等待服务器给你返回的数据进行处理就行了(我用的是eventbus来发送数据到activity中处理的)

OK,现在开始编写nodejs的代码

首先大家应该先入门nodejs哈…安装并配置nodejs 后,只需要在同一个文件夹中有如下图几个东西就行了



然后就是websocket.js里的内容了,(比较简单的内容,复杂的可以自己慢慢研究, 当然里面有什么错误了请谅解….)

var ws= require("nodejs-websocket");

var server = ws.createServer(function(conn){

var timestamp = new Date().getTime();
console.log('new websocket connection open: %d', timestamp);
conn.userId = timestamp;//这里是存入一个唯一的标识符
conn.send(JSON.stringify({msgType:'onOpenConnection', msg:{connectionId:timestamp}}));

//从前端收到信息
conn.on("text", function (str) {
console.log("get:"+str);

//直接发送收到的消息
conn.send(JSON.stringify(str));

});

conn.on("close", function (code, reason ) {
console.log("----->>>>" +  "----" + code + "----" + conn.userId + "===");
console.log("close");
});

conn.on("error", function (code, reason) {
console.log("异常关闭");
});
}).listen(8010);//下面必须看 要不android端搜不到

console.log('websocket server created');


这里来说一下自己写的nodejs,在android网路请求搜不到,自己解决是用 360wifi 在电脑打开,手机连上这个wifi。 因为是本地ip的原因,这里先在命令行输入ipconfig 得到自己的IP地址(ipv4 …. 172.17.4.31 这是我的),首先地址写成自己的,然后把代码运行到手机上就可以测试了(如果有什么问题 ,请评论 我在完善下 谢谢)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  websocket nodejs
相关文章推荐