Android中使用WebSocket

2017-12-25
背景:后端逻辑框架调整,将原来的推送和轮询方式改成了使用WebSocket通信。原来的请求方式是由app发起请求,appServer对请求进行分发,中转中继服务器将具体请求下发到对应的物联网服务器,物联网服务器将指令下发到指定的设备。整个流程涉及到很多层http请求,并且每个服务的回调接口还不一致,只能在app发情请求之后,接着去轮询服务器,服务器端去查询设备状态、是否对指令有响应。
改版后涉及到对物联网的请求全部改成WebSocket,不在轮询,而是被动等待。
后端使用的是Spring实现的WebSocket,app端使用的是https://github.com/TooTallNate/Java-WebSocket这个开源项目。

APP端实现
  1. 添加依赖compile "org.java-websocket:Java-WebSocket:1.3.7"
  2. 我们只需要关心三方库中WebSocketClient类就可以了,其他细节底层已经封装好了。
  3. 类中有四个方法需要重写:
/**打开连接*/
 public void onOpen(ServerHandshake handshakedata)
 /**服务端返回消息*/
 public void onMessage(String message) 
 /**关闭连接*/
 public void onClose(int code, String reason, boolean remote)
 /**出现异常*/
 public void onError(Exception ex)
  1. 一个简单的小测试,app端定义了一个发送按钮,和一个展示消息的文本

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.huangyuanlove.testwebsocket.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <TextView
            android:id="@+id/show_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edit_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:padding="10dp"
            androi

你可能感兴趣的:(android,websocket,android)