当前位置:   article > 正文

Java实现WebSocket客户端与服务端_java websocket 是客户端有事服务端

java websocket 是客户端有事服务端

依赖

客户端:

<dependency>
	<groupId>org.java-websocket</groupId>
	<artifactId>Java-WebSocket</artifactId>
	<version>1.3.8<version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

服务端:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • 1
  • 2
  • 3
  • 4

客户端

@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);
			}
		}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

服务端(to One)

@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();
			}
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

客户端重连(定时任务)

@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的包没有这个方法
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/249108
推荐阅读
相关标签
  

闽ICP备14008679号