服務端代碼:java
package com.xxg.websocket; import java.io.IOException; import java.io.InputStream; import java.net.URI; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.RemoteEndpoint.Basic; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint 標註的是多實例 的 * @author Administrator * */ @ServerEndpoint("/log") // 服務點 public class LogWebSocketHandle { private int count = 0; /** * 新的WebSocket請求開啓 * 鏈接創建成功調用的方法 * @param session 可選的參數。session爲與某個客戶端的鏈接會話,須要經過它來給客戶端發送數據 */ @OnOpen public void onOpen(Session session) { System.out.println("onOpen start"); try { Basic basicRemote = session.getBasicRemote(); URI requestURI = session.getRequestURI(); basicRemote.sendText(requestURI.getPath()+requestURI.getQuery()); } catch (IOException e) { e.printStackTrace(); }finally { } } /** * 收到客戶端消息後調用的方法 * @param message 客戶端發送過來的消息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session){ System.out.println("client message "+message); final Session session1 = session; try { session.getBasicRemote().sendText(" say count "+(++count)); session.getBasicRemote().flushBatch(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { while(true){ session1.getBasicRemote().sendText("hello benny" + (++count)+"\r\n"); session1.getBasicRemote().flushBatch(); Thread.sleep(1000); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * WebSocket請求關閉 * 鏈接關閉調用的方法 */ @OnClose public void onClose() { System.out.println("onClose end"); } /** * 發生錯誤時調用 * @param session * @param error */ @OnError public void onError(Throwable thr) { thr.printStackTrace(); } }
客戶端依賴:web
<dependency> <groupId>org.glassfish.tyrus.bundles</groupId> <artifactId>tyrus-standalone-client</artifactId> <version>1.13</version> </dependency>
客戶端的類庫,千萬不要使用下面這段。api
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-client-api</artifactId> <version>1.1</version> </dependency>
若是使用上面的類庫會出現下面異常websocket
Exception in thread "main" java.lang.RuntimeException: Could not find an implementation class. at javax.websocket.ContainerProvider.getWebSocketContainer(ContainerProvider.java:73) at connect.<init>(connect.java:21) at test.main(test.java:11)
解決方法:http://stackoverflow.com/questions/27751630/websocket-client-could-not-find-an-implementation-class stackoverflow 上的大牛解釋session
javax.websocket api is only the specification don't have full implementation you may need to take the jar file tyrus-standalone-client-1.9.jar and try the same example that should solve your problem. i tested with my example and it is working fine.
客戶端代碼:socket
package com.xxg.websocket.client; import java.io.IOException; import java.net.URI; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; @ClientEndpoint public class WebSocketClient { private Session session = null; private int count = 0; @OnOpen public void onOpen(Session session){ sendMessage("onOpen hello benny onOpen"); } @OnClose public void onClose(){ } @OnMessage public void onMessage(String message, Session session){ System.out.println("server message:"+message); if(count <10){ sendMessage("onMessage hello benny "+(++count)); } } @OnError public void onError(Throwable thr){ } public WebSocketClient() { super(); } public WebSocketClient(URI endpointURI) { super(); try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 得到WebSocketContainer this.session = container.connectToServer(WebSocketClient.class, endpointURI); // 該方法會阻塞 } catch (Exception e) { throw new RuntimeException(e); } } public Session getSession() { return session; } public void setSession(Session session) { this.session = session; } public void sendMessage(String message){ try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { this.session.getBasicRemote().flushBatch(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }