赞
踩
客户端:
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.8<version>
</dependency>
服务端:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
@Slf4j @Component public class SocketClient { @Bean public WebSocketClient webSocketClient(){ try{ WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://localhost:8090/test-one"),new Draft_6455()){ @Override public void onOpen(ServerHandshake handshakedata){ log.info("[websocket]连接成功"); //webSocketClient.send需在onOpen回调之后,即于客户端建立连接之后 //测试代码 ThreadPoolManager.getInstance().execute(new Task(this)); } @Override public void onMessage(String message){ log.info("accept message success is {}",message); //执行接收到消息体后的相应操作 } @Override public void onClose(int code,String reason,boolean remote){ log.info("[websocket]退出连接") } @Override public void onError(Exception ex){ log.info("[websocket]连接错误",ex); } }; webSocketClient.connect(); return webSocketClient; } catch(Exception e){ e.printStackTrace(); } return null; } class Task implements Runnable{ public WebSocketClient webSocketClient; Task(WebSocketClient webSocketClient){ this.webSocketClient = webSocketClient; } } @SneakeyThrows @Override public void run(){ while(true){ webSocketClient.send("client test message"); Thread.sleep(1000); } } }
@ServerEndpoint("/test-one") @Component @Slf4j public class OneToOneServer{ /** * 用于存放所有在线客户端 */ private static Map<String,Session> clients = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session){ log.info("有新的客户端上线,客户端id:{}",session.getId()); //解决数据字节过多,客户端连接中断,默认8190; //字节过多也可采用分片 session.setMaxTextMessageBufferSize(81900); clients.put(session.getId(),session); } @OnClose public void onClose(Session session){ String clientId = session.getId(); log.info("有客户端离线,客户端Id:{}",clientId); clients.remove(clientId); } @OnError public void onError(Session session,Throwable throwable){ String clientId = session.getId(); if(clients.get(clientId) != null){ log.info("发生了错误,移除客户端:{}",clientId); clients.remove(clientId); } throwable.printStackTrace(); } @OnMessage public void onMessage(String message,Session session){ log.info("收到客户端{}发来的消息",message); String test = "server test message"; sendTo(session.getId(),test); } /** * 发送消息 * @param clientId */ private void sendTo(String clientId,String message){ Session session = clients.get(clientId); if(session != null){ try{ session.getBasicRemote().sendText(message); } catch(IOException e){ e.printStackTrace(); } } } }
@Component @Slf4j public class WebSocketHearBeat{ //重连简单实现 @Autowired private WebSocketClient webSocketClient; @Scheduled(cron = "5/2 * * * * ?") public void heartBeat(){ try{ webSocketClient.sendPing(); } catch(Exception e){ log.info("断开连接 开始重试"); webSocketClient.reconnect(); //1.3.5的包没有这个方法 } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。