JAVA实现websocket客户端

 

 

pom依赖

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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

 

fastjson是用来发送json数据的 可以用自己的

 

 

MyWebSocketClient.java
import java.net.URI;
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  websocket客户端监听类
 * @author*/
public class MyWebSocketClient extends WebSocketClient {

    private static Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);

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

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        logger.info(">>>>>>>>>>>websocket open");
    }

    @Override
    public void onMessage(String s) {
        logger.info(">>>>>>>>>> websocket message");
       
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.info(">>>>>>>>>>>websocket close");
    }

    @Override
    public void onError(Exception e) {
        logger.error(">>>>>>>>>websocket error {}",e);
    }


}

 

使用

 public static void main(String[] args) {
        try {
            MyWebSocketClient myClient = new MyWebSocketClient(new URI("ws://192.168.2.20:8080"));
            myClient.connect();
            while (!myClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                System.out.println("连接中。。。");
                Thread.sleep(1000);
            }
            // 连接成功往websocket服务端发送数据
            JSONObject object = new JSONObject();
            object.put("message", "success连接");
            myClient.send(object.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

 

使用完之后 可以调用myClient.close()方法关闭

 

posted @ 2021-09-27 14:19  yvioo  阅读(9007)  评论(1编辑  收藏  举报