Java教程

JAVA实现websocket客户端

本文主要是介绍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 one rror(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();
        }
    }

 

这篇关于JAVA实现websocket客户端的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!