简介

本Demo演示了S-SDK部分API的调用方法,包括注册用户、连接服务器、点对点消息、发布订阅主题等功能。  


运行环境

  • 依赖 Java SE 7 (1.7 及以上版本)
  • slf4j-api 日志库 (1.7.13 及以上版本)
 


应用实例

公共变量设置

  • 该设置为以下SDK公用变量
  •     public static final String CHARACTER_UTF8 = "UTF-8";
        public static final String APP_KEY = "您的AppKey";
        public static final String SECRET_KEY = "您的SceretKey";
        public static final String UID = "你的UID";
        public static final String RECEIVE_UID = "接收消息的UID";
        public static final String DOMAIN = "服务器域名或IP";
        public static final int PORT = 8085; // 服务器默认端口.
        public static final String TOPIC = "testPublish"; // 示例主题.
        public static EtFactory factory; // SDK工厂.
        public static ISDK sdk; // SDK服务管理器.
        private static IContext etContext; // SDK上下文.
        

1. 创建EtFactory、EtManager对象实例

  1. 通过SDK工厂可以创建EtManager管理器,和http管理实例.。
  2. EtFactory f = new EtFactory();
    IContext ctx = f.createContext();
    ctx.setAppKey(APP_KEY).setSecretKey(SECRET_KEY).setUserName(UID).setServerDomain(DOMAIN).setServerPort(PORT);
    final ISDK sdk = f.createSDK(ctx);
                    

2. 设置回调

  • 设置回调监听器。
  • 
    sdk.setCallback(new IReceiveListener() {
    	@Override
    	public void connectionLost(int reasonCode, Throwable cause) {
    		System.err.println("~~~~~~~~~~~~~reasonCode=" + reasonCode);
    		cause.printStackTrace();
    	}
    
    	@Override
    	public void onMessage(String topic, byte[] payload) {
    		System.out.println("~~~~~~~~~~~~~topic=" + topic + ". payload=" + new String(payload));
    	}
    });
    
                    

 

3. 注册用户(UID)(非必须设置)

  • 首次使用,需要注册用户,下例中,通过EtFactory工厂直接获得基础的Web管理器进行注册。
  • 也可以注册后台管理界面上生成更多的用户。
  • 
    EtFactory f = new EtFactory();
    IWeb iw = f.createWeb();
    final CountDownLatch cdl1 = new CountDownLatch(1);
    iw.addUser(APP_KEY, SECRET_KEY, DOMAIN, 8085, "testSSDK0", "test_ssdk0", new ICallback() {
    	@Override
    	public void onSuccess(String json) {
    		JSONObject jo = JSON.parseObject(json);
    		int returnCode = jo.getInteger(EtConstants.MSG_RESPONSE_CODE);
    		String returnInfo = (String) jo.get(EtConstants.MSG_RESPONSE_CONTENT);
    		if (0 != returnCode) {
    			System.err.println("~~~~~~~~~~~~~~~addUser not onSuccess. " + returnInfo);
    		} else {
    			System.out.println("~~~~~~~~~~~~~~~addUser onSuccess. " + json);
    		}
    		cdl1.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable ex) {
    		System.err.println("~~~~~~~~~~~~~~~addUser onFailure. " + ex);
    		cdl1.countDown();
    	}
    });
    try {
    	cdl1.await();
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
    
                    

4. 连接服务器

  • 设置连接监听器后,连接ET-iLink服务器。
  • 连接监听器之前,需要先发现服务器。通过discoverServers函数实现
  • 
    
    // 发现服务器.
    final CountDownLatch cdl = new CountDownLatch(1);
    sdk.discoverServers(TIMEOUT, new ICallback() {
    	@Override
    	public void onSuccess(EtServerInfo etServerInfo) {
    		System.err.println(String.format("onSuccess return EtServerInfo = %s", etServerInfo.toString()));
    		serverInfo = etServerInfo;
    		cdl.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable value) {
    		System.err.println(String.format("discoverServers() is failed, occur = %s", value.getLocalizedMessage()));
    		cdl.countDown();
    	}
    });
    cdl.await();
    
    
    
    // 连接服务器.
    final CountDownLatch cdl2 = new CountDownLatch(1);
    sdk.connect(serverInfo, (short) 15, true, 8, new ICallback() {
    	@Override
    	public void onSuccess(Void aVoid) {
    		System.out.println(Thread.currentThread().getName() + "~~~~~~~~~connect()成功");
    		cdl2.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable ex) {
    		System.err.println(Thread.currentThread().getName() + ex);
    	}
    });
    cdl2.await();
    
                    

5. 点对点消息收发

  • 以点对点的方式发消息到RECEIVE_UID账户中。
  • 以下示例消息内容可以是字符串和字节数组形式。
  • 
    
    String msg = MSG_CONTENT;
    msg = toChangeByHex(msg.getBytes());
    
    final CountDownLatch cdl3 = new CountDownLatch(1);
    sdk.chatTo(RECEIVE_UID, msg.getBytes(), new ICallback() {
    	@Override
    	public void onSuccess(Void aVoid) {
    		System.out.println("~~~~~~~~~chatTo(" + RECEIVE_UID + ")成功");
    		cdl3.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable ex) {
    		System.err.println("*********chatTo(" + RECEIVE_UID + ")失败. " + ex.getLocalizedMessage());
    		cdl3.countDown();
    	}
    });
    cdl3.await();
    
                    

6. 订阅

  • 订阅主题TOPIC。
  • 
    final CountDownLatch cdl4 = new CountDownLatch(1);
    sdk.subscribe(TOPIC, QosLevelEnum.QoS_1, new ICallback() {
    	@Override
    	public void onSuccess(EtAck etAck) {
    		System.out.println(String.format("~~~~~~~~~subscribe(%s, %d)成功. threadName=%s", TOPIC, QosLevelEnum.QoS_1.getCode(), Thread.currentThread().getName()));
    		cdl4.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable ex) {
    		cdl4.countDown();
    	}
    });
    try {
    	cdl4.await();
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
                    

7. 发布

  • 发布主题TOPIC。
  • 
    String msg = toChangeByHex(MSG_CONTENT.getBytes());
    final CountDownLatch cdl5 = new CountDownLatch(1);
    sdk.publish(TOPIC, msg.getBytes(), QosLevelEnum.QoS_1, new ICallback() {
    	@Override
    	public void onSuccess(Void v) {
    		System.out.println(String.format("~~~~~~~~~publish(%s, %d)成功. threadName=%s", TOPIC, QosLevelEnum.QoS_1.getCode(), Thread.currentThread().getName()));
    		cdl5.countDown();
    	}
    
    	@Override
    	public void onFailure(Throwable ex) {
    		ex.printStackTrace();
    		cdl5.countDown();
    	}
    });
    try {
    	cdl5.await();
    } catch (InterruptedException e) {
    	e.printStackTrace();
    }
    
                    

8. 订阅用户上下线状态.

  • 订阅用户上下线时,需要在未登录前设置 用户在线离线状态监听器.。
  • 
    // 用户在线离线状态监听器.
    sdk.setUserStatusListener(new IUserStatusListener() {
        @Override
        public void concernOnlineStatus(String userId, String statusCode) {
            System.out.println("~~~~~~~~~~~~~userId=" + userId + ", online status=" + statusCode);
        }
    });
    
    //--------- setUserStatusListener 状态监听器只需设置一次,应该放在2. 设置回调 节点之后。---------
    
    final CountDownLatch cdl4 = new CountDownLatch(1);
    sdk.subUserState(testSSDK2, new ICallback() {
        @Override
        public void onSuccess(Void aVoid) {
            System.out.println(String.format("~~~~~~~~~subUserState(%s)成功. threadName=%s", TOPIC, Thread.currentThread().getName()));
            cdl4.countDown();
        }
    
        @Override
        public void onFailure(Throwable ex) {
            ex.printStackTrace();
            cdl4.countDown();
        }
    });
    try {
        cdl4.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
                    

9. 取消订阅用户上下线状态

  • 取消RECEIVE_UID用户的上下线状态。
  • 
    final CountDownLatch cdl4 = new CountDownLatch(1);
    sdk.subUserState(testSSDK2, new ICallback() {
        @Override
        public void onSuccess(Void aVoid) {
            System.out.println(String.format("~~~~~~~~~subUserState(%s)成功. threadName=%s", TOPIC, Thread.currentThread().getName()));
            cdl4.countDown();
        }
    
        @Override
        public void onFailure(Throwable ex) {
            ex.printStackTrace();
            cdl4.countDown();
        }
    });
    try {
        cdl4.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
                    

10. 释放资源

  • 是否SDK中所有的资源,该方法调用后,请不要再使用任何SDK资源。
  • 
    sdk.destroy(); //释放SDK资源.