java|android 使用SocketIO.jar连接nodejs websocket
电脑版发表于:2019/8/13 11:21
socket.io-client版连接nodejs websocket
http://www.tnblog.net/aojiancc2/article/details/2562
一:更具url建立连接,调用想要的方法
SocketIO socket; try { socket = new SocketIO("url"); socket.connect(new IOCallback() { public void onMessage(JSONObject json, IOAcknowledge ack) { try { System.out.println("there Server said:" + json.toString(2)); } catch (JSONException e) { e.printStackTrace(); } } public void onMessage(String data, IOAcknowledge ack) { try { System.out.println(" 22 Server said: " + data); } catch(Exception e) { System.out.println("xxxxxxxxx:"+e.getMessage()); } } public void onError(SocketIOException socketIOException) { System.out.println("an Error occured:"+socketIOException.getMessage()); socketIOException.printStackTrace(); } public void onDisconnect() { System.out.println("Connection terminated."); } public void onConnect() { System.out.println("Connection established"); } public void on(String event, IOAcknowledge ack, Object... args) { System.out.println("Server triggered event '" + event + "'"); for(int i=0;i<args.length;i++){ System.out.println("参数 '"+i+":" +args[i] ); } } });
onMessage是默认的方法,只要连接成功服务端就可以通过message向你发送数据
客户端onMessage会自动回调
但是服务器端会有很多自定义方法,怎么让服务器端知道我们想要调用的方法,就需要用到emit,向服务器端传递方法名与参数.
socket.emit("wayname","params");
传递json参数:
JSONObject json = new JSONObject(); json.putOpt("aa", "106"); json.putOpt("bb", "29"); socket.emit("wayname",json);
这时服务器一般会用其他方法进行回调而不是onMessage,一般在on方法里:
public void on(String event, IOAcknowledge ack, Object... args) { System.out.println("服务器回调了:方法名 '" + event + "'"); for(int i=0;i<args.length;i++){ System.out.println("参数 '"+i+":" +args[i] ); } }
二:设置header,传cookies等:
socket.addHeader("Cookie", "laravel_session=" + LoginActivity.PHPSESSID);