websocket的java客戶端,使用Tomcat中的websocket搭建
阿新 • • 發佈:2018-11-08
pom.xml的配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>
客戶端的寫作:
import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Timer; import java.util.TimerTask; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ClientEndpoint public class SocketClient{ public static Session session; public static boolean CLOSED = false; private final static Logger LOG = LoggerFactory.getLogger(SocketClient.class); static Timer timer = null; static Mytask timerTask = null; @OnOpen public void onOpen(Session session1) { session = session1; heart(); } @OnMessage public void onMessage(String msg) { LOG.info(msg); new DealMsg().dealMsg(msg); } @OnError public void onError(Throwable t) { LOG.info("連線錯誤的斷開"); t.printStackTrace(); try { connection(); } catch (Exception e) { e.printStackTrace(); } } @OnClose public void onClose() { LOG.info("連線伺服器關閉"); CLOSED = true; } public static void send(String message){ if (session.isOpen()) { LOG.info("send:" + message); session.getAsyncRemote().sendText(message); } } public static void close() { if (session != null) { try { session.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void connection() throws DeploymentException, IOException, URISyntaxException { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 獲取WebSocket聯結器,其中具體實現可以參照websocket-api.jar的原始碼,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer"); String uri = "連線的伺服器地址"; SocketClient sc = new SocketClient(); container.connectToServer(sc, new URI(uri)); CLOSED = false; } // 心跳,每55秒傳送一次 public void heart() { timer = new Timer(true); timerTask = new Mytask(); timer.scheduleAtFixedRate(timerTask, 55000, 55000); } // 重置心跳 public void resetHeart() { if (timer != null) { if (timerTask != null) { timerTask.cancel(); } timerTask = new Mytask(); timer.scheduleAtFixedRate(timerTask, 0, 55000); } } } class Mytask extends TimerTask { @Override public void run() { //寫出自己定時器操作的程式碼 } }