java 作为客户端

依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

 

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import icil.common.websocket.handler.WSClientHandler;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.ContainerProvider;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.net.URI;
import java.util.concurrent.TimeUnit;

/************************************
 * <pre>
 * @PACKAGE  : sea.common.websocket.handler
 * @Author   : Sea
 * @Date     : 2022/4/3 14:27
 * @Desc     :
 * @History  :
 * <pre/>
 ***********************************/
@Slf4j
public class MyWSClientUtils {

    private static String HEARTBEAT="ping";
    private static  Cache<String,Session> wsCache = CacheBuilder.newBuilder()
            .initialCapacity(3)
            .expireAfterWrite(10, TimeUnit.HOURS) //10h 防止无用的session
            .build();

    /**
     * @param uri "ws://192.168.18.51:7206/websocket/001/Sea/1"
     */
    public static synchronized Session connectWS(String uri){
        Session sessionInCache = wsCache.getIfPresent(uri);
        if(sessionInCache!=null&&sessionInCache.isOpen()){return sessionInCache;}
        try{
            if(sessionInCache!=null){sessionInCache.close();}
            log.info("start connect ws : {}",uri);
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            //设置消息大小最大为20M
            container.setDefaultMaxBinaryMessageBufferSize(20*1024*1024);
            container.setDefaultMaxTextMessageBufferSize(20*1024*1024);
            // 客户端,开启服务端websocket。
            Session session = container.connectToServer(WSClientHandler.class,URI.create(uri));
            session.setMaxIdleTimeout(60*60*1000);// 1h
            session.getBasicRemote().sendText(HEARTBEAT);
            wsCache.put(uri,session);
            return  session;
          } catch (Exception ex) {
            ex.printStackTrace();
            log.warn("c出错了 connect ws:{} exp:{}",uri,ex);
        }
            return  null;
    }

    /**
     * @param msg
     * @param uri : "ws://192.168.18.51:7206/ws/001/xx/1"
     * @return
     */
    public static Boolean sendMsg(String msg,String uri) {
        try
        {
            Session session = connectWS(uri);
            session.getBasicRemote().sendText(msg);
            return true;
        }catch (Exception e){
            log.error("send msg exp:{}",e);
            return false;
        }
    }
}

 

 

package sea.common.websocket.handler;
import lombok.extern.slf4j.Slf4j;
import javax.websocket.*;

/************************************
 * <pre>
 * @PACKAGE  : sea.common.websocket.handler
 * @Author   : Sea
 * @Date     : 2022/4/3 14:23
 * @Desc     :
 * @History  : who date todo
 * <pre/>
 ***********************************/
@ClientEndpoint
@Slf4j
public class WSClientHandler {
    @OnOpen
    public void onOpen(Session session) {
        log.info("连接成功!"+session.getId());//上面默认是1h, 断了重新连接就就好
//        new Thread(()->{
//           try {
//               while (true){
////                   Thread.sleep(5*60*1000l); //5min send heartbeat
//                   Thread.sleep(3*1000l); //5min send heartbeat
//                   session.getBasicRemote().sendText("ping");
//               }
//           }catch (Exception e){}
//        }).start();
    }
    @OnMessage
    public void processMessage(String message,Session session) {
        log.info("ws client 接收推送消息"+message);

    }
    @OnError
    public void processError(Throwable t) {
        log.error("---ws client processError error---", t);
    }

    @OnClose
    public void processClose(Session session, CloseReason closeReason) {
        log.error(session.getId() + closeReason.toString());
    }
}

 

 

 

方式2:  

依赖:

         <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.5.1</version>
        </dependency>

 

MyWebSocketClient.java
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

public class MyWebSocketClient extends WebSocketClient {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info("[MyWebSocketClient#onOpen]The WebSocket connection is open.");
    }

    @Override
    public void onMessage(String s) {
        logger.info("[MyWebSocketClient#onMessage]The client has received the message from server." +
                "The Content is [" + s + "]");
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.info("[MyWebSocketClient#onClose]The WebSocket connection is close.");
    }

    @Override
    public void onError(Exception e) {
        logger.info("[MyWebSocketClient#onError]The WebSocket connection is error.");
    }
}

 

test:

public class WebSocketTest {
    private static final AtomicInteger count = new AtomicInteger(0);

    @Test
    public void test() {
        URI uri = URI.create("ws://127.0.0.1:8081/websocket");  
        MyWebSocketClient client = new MyWebSocketClient(uri);
        client.addHeader("token", "mytoken");              //这里为header添加了token,实现简单的校验
        try {
            client.connectBlocking();   //在连接成功之前会一直阻塞

            while (true) {
                if (client.isOpen()) {
                    client.send("hello ");
                }
                Thread.sleep(10000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

 

posted on 2022-08-09 15:42  lshan  阅读(153)  评论(0编辑  收藏  举报