// 使用的jar包: https://github.com/TooTallNate/Java-WebSocket
// websocket参考网站
// jar包原想上传的,但在CSDN找不到上传的地方
// 主要的类import java.net.URI; import java.util.concurrent.CountDownLatch; import org.java_websocket.handshake.ServerHandshake; import com.zmy.util.Comn; public class WebSockStu { public static void main(String[] args){ t(); } public static String t(){ String uri = "wss://api.radarlab.org:443"; uri="ws://api.radarlab.org:5006"; WebSocketClientExt cc=null; try{ cc = new WebSocketClientExt(new URI(uri)){ @Override public void onMessage( String message ) { setMsg(message); Comn.pl( "got: " + message + "\n" ); getCdl().countDown(); } @Override public void onOpen( ServerHandshake handshake ) { getCdlConn().countDown(); Comn.pl( "You are connected to ChatServer: " + getURI() + "\n" ); } @Override public void onClose( int code, String reason, boolean remote ) { Comn.pl( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" ); } @Override public void onError( Exception ex ) { Comn.pl( "Exception occured ...\n" + ex + "\n" ); ex.printStackTrace(); } }; }catch(Exception e){ e.printStackTrace(); } cc.connect(); try{ CountDownLatch cdl = new CountDownLatch(1); cc.setCdlConn(cdl); cdl.await(); }catch(Exception e){ e.printStackTrace(); } String m="{\"id\": 2,\"command\": \"account_info\",\"account\": \"rLnR6ruCzsHRvhEAGMsr2kDHWNCMhs2hZc\",\"strict\": true,\"ledger_index\": \"validated\" }"; byte[] b = null; try{ b=m.getBytes("UTF-8"); }catch(Exception e){ e.printStackTrace(); } cc.send(b); try{ CountDownLatch cdl = new CountDownLatch(1); cc.setCdl(cdl); cdl.await(); }catch(Exception e){ e.printStackTrace(); } Comn.pl("return:"+cc.getMsg()); cc.close(); return cc.getMsg(); } }
// 素材类
import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.java_websocket.client.WebSocketClient; public abstract class WebSocketClientExt extends WebSocketClient{ public WebSocketClientExt(URI serverURI){ super(serverURI); } private List<Object> objs = new ArrayList<Object>(); private String msg = null; private CountDownLatch cdl = null; private CountDownLatch cdlConn = null; public List<Object> getObjs() { return objs; } public void setObjs(List<Object> objs) { this.objs = objs; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public CountDownLatch getCdl() { return cdl; } public void setCdl(CountDownLatch cdl) { this.cdl = cdl; } public CountDownLatch getCdlConn() { return cdlConn; } public void setCdlConn(CountDownLatch cdlConn) { this.cdlConn = cdlConn; } }
public class Comn { public static void main(String[] args) { } public static void p(Object o) { System.out.print(o); } public static void pl(Object o) { System.out.println(o); } }
// 欢迎大家交流
通过CountDownLatch实现websocket同步返回
原文地址:http://blog.csdn.net/lijunwyf/article/details/46506867