排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术
原
java|android 使用socket.io-client连接nodejs websocket
分类:
Java
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(); } }
mave:
<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);
少侠,我看你气度不凡天赋异禀,这么帅,来了就给关注一波呗
欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739
评价