java|android 使用socket.io-client连接nodejs websocket


socket.io-client相比SocketIO.jar使用起来更方便一点

 public void connection(final MapAction _action) {
			
			try {
				IO.Options opts = new IO.Options();
				opts.query = "w_auth_key=" +LoginActivity.socket_auth_key;//传参数
				Socket socket = IO.socket("ip/", opts);
				socket.connect();
				socket.emit("initAllShips");//请求websocket后台方法
				
				socket.on("setInitShips", new Emitter.Listener() { //监听回调函数
					  @Override
					  public void call(Object... args) {
					        System.out.println("回调了参数:"+args[0]);
					  }
					});
			    
				
			} catch (Exception e1) {
				e1.printStackTrace();
			}
	}


maven 

<dependencies>
  <dependency>
    <groupId>com.github.nkzawa</groupId>
    <artifactId>socket.io-client</artifactId>
    <version>0.5.0</version>
  </dependency>
</dependencies>


socket = IO.socket("http://localhost");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

  @Override
  public void call(Object... args) {
    socket.emit("foo", "hi");
    socket.disconnect();
  }

}).on("event", new Emitter.Listener() {

  @Override
  public void call(Object... args) {}

}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

  @Override
  public void call(Object... args) {}

});
socket.connect();

This Library uses  org.json  to parse and compose JSON strings:

// Sending an object
JSONObject obj = new JSONObject();
obj.put("hello", "server");
obj.put("binary", new byte[42]);
socket.emit("foo", obj);

// Receiving an object
socket.on("foo", new Emitter.Listener() {
  @Override
  public void call(Object... args) {
    JSONObject obj = (JSONObject)args[0];
  }
});
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.query = "auth_token=" + authToken;
Socket socket = IO.socket("http://localhost", opts);





你可能感兴趣的:(java|android 使用socket.io-client连接nodejs websocket)