javax.websocket客户端简单的例子

有人可以提供我使用javax.websocket的websocket客户端的非常简单的例子吗?

我想连接到websocket(ws://socket.example.com:1234),发送消息(添加通道)并收听消息。 所有消息(发送和收听)都是JSON格式。

顺便说一句,这个库是最简单的websocket通信?

(抱歉,愚蠢的问题,我正在学习Java,谢谢)

我在这里find了一个使用javax.websocket的好例子:

http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html

这里的代码基于上面链接的例子:

TestApp.java

 package testapp; import java.net.URI; import java.net.URISyntaxException; public class TestApp { public static void main(String[] args) { try { // open websocket final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi")); // add listener clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() { public void handleMessage(String message) { System.out.println(message); } }); // send message to websocket clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}"); // wait 5 seconds for messages from websocket Thread.sleep(5000); } catch (InterruptedException ex) { System.err.println("InterruptedException exception: " + ex.getMessage()); } catch (URISyntaxException ex) { System.err.println("URISyntaxException exception: " + ex.getMessage()); } } } 

WebsocketClientEndpoint.java

 package testapp; import java.net.URI; import javax.websocket.ClientEndpoint; import javax.websocket.CloseReason; import javax.websocket.ContainerProvider; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; /** * ChatServer Client * * @author Jiji_Sasidharan */ @ClientEndpoint public class WebsocketClientEndpoint { Session userSession = null; private MessageHandler messageHandler; public WebsocketClientEndpoint(URI endpointURI) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(this, endpointURI); } catch (Exception e) { throw new RuntimeException(e); } } /** * Callback hook for Connection open events. * * @param userSession the userSession which is opened. */ @OnOpen public void onOpen(Session userSession) { System.out.println("opening websocket"); this.userSession = userSession; } /** * Callback hook for Connection close events. * * @param userSession the userSession which is getting closed. * @param reason the reason for connection close */ @OnClose public void onClose(Session userSession, CloseReason reason) { System.out.println("closing websocket"); this.userSession = null; } /** * Callback hook for Message Events. This method will be invoked when a client send a message. * * @param message The text message */ @OnMessage public void onMessage(String message) { if (this.messageHandler != null) { this.messageHandler.handleMessage(message); } } /** * register message handler * * @param msgHandler */ public void addMessageHandler(MessageHandler msgHandler) { this.messageHandler = msgHandler; } /** * Send a message. * * @param message */ public void sendMessage(String message) { this.userSession.getAsyncRemote().sendText(message); } /** * Message handler. * * @author Jiji_Sasidharan */ public static interface MessageHandler { public void handleMessage(String message); } } 

TooTallNate有一个简单的客户端https://github.com/TooTallNate/Java-WebSocket

只需将dist文件夹中的java_websocket.jar添加到您的项目中。

  import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_10; import org.java_websocket.handshake.ServerHandshake; import org.json.JSONException; import org.json.JSONObject; WebSocketClient mWs = new WebSocketClient( new URI( "ws://socket.example.com:1234" ), new Draft_10() ) { @Override public void onMessage( String message ) { JSONObject obj = new JSONObject(message); String channel = obj.getString("channel"); } @Override public void onOpen( ServerHandshake handshake ) { System.out.println( "opened connection" ); } @Override public void onClose( int code, String reason, boolean remote ) { System.out.println( "closed connection" ); } @Override public void onError( Exception ex ) { ex.printStackTrace(); } }; //open websocket mWs.connect(); JSONObject obj = new JSONObject(); obj.put("event", "addChannel"); obj.put("channel", "ok_btccny_ticker"); String message = obj.toString(); //send message mWs.send(message); 

//并closureswebsocket

  mWs.close(); 

看看Arun Gupta的Java EE 7示例。

我在github上分叉了它。

主要

 /** * @author Arun Gupta */ public class Client { final static CountDownLatch messageLatch = new CountDownLatch(1); public static void main(String[] args) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); String uri = "ws://echo.websocket.org:80/"; System.out.println("Connecting to " + uri); container.connectToServer(MyClientEndpoint.class, URI.create(uri)); messageLatch.await(100, TimeUnit.SECONDS); } catch (DeploymentException | InterruptedException | IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } } 

ClientEndpoint

 /** * @author Arun Gupta */ @ClientEndpoint public class MyClientEndpoint { @OnOpen public void onOpen(Session session) { System.out.println("Connected to endpoint: " + session.getBasicRemote()); try { String name = "Duke"; System.out.println("Sending message to endpoint: " + name); session.getBasicRemote().sendText(name); } catch (IOException ex) { Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex); } } @OnMessage public void processMessage(String message) { System.out.println("Received message in client: " + message); Client.messageLatch.countDown(); } @OnError public void processError(Throwable t) { t.printStackTrace(); } } 

这里有一个简单的例子..你可以下载并testing它http://www.pretechsol.com/2014/12/java-ee-websocket-simple-example.html