websocket是H5新推出的协议,一般用于前端,但是在实际项目中我们需要用java代码来获取一些设备的实时运行数据,在后台处理后推送的前台界面,为了保证实时性,我们需要用到websocket协议,而刚好有一个叫java-websocket的开源项目,我们可以利用它来实现java版的websocket client。
1、需要引入的依赖:
<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.3.5</version> </dependency>
2、客户端代码
package com.example.demo; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import org.java_websocket.WebSocket; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; public class MyWebSocketClient extends WebSocketClient{ public MyWebSocketClient(String url) throws URISyntaxException { super(new URI(url)); } @Override public void onOpen(ServerHandshake shake) { System.out.println("握手..."); for(Iterator<String> it=shake.iterateHttpFields();it.hasNext();) { String key = it.next(); System.out.println(key+":"+shake.getFieldValue(key)); } } @Override public void onMessage(String paramString) { System.out.println("接收到消息:"+paramString); } @Override public void onClose(int paramInt, String paramString, boolean paramBoolean) { System.out.println("关闭..."); } @Override public void onError(Exception e) { System.out.println("异常"+e); } public static void main(String[] args) { try { MyWebSocketClient client = new MyWebSocketClient("ws://192.168.1.118:8080/websocket"); client.connect(); while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) { System.out.println("还没有打开"); } System.out.println("建立websocket连接"); client.send("asd"); } catch (URISyntaxException e) { e.printStackTrace(); } } }
3、启动websocket server,可参考我的博客https://www.cnblogs.com/hhhshct/p/9507146.html,然后直接main方法运行,结果如下: