<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
package batteryplatform;
import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
public class WebsocketClientTest {
public static void main(String[] args) throws Exception {
URI uri = new URI("ws://localhost:8080/websocket/bigscreen3");
WebSocketClient c = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake handshakedata) {
}
@Override
public void onMessage(String message) {
System.err.println(message);
}
@Override
public void onClose(int code, String reason, boolean remote) {
}
@Override
public void onError(Exception ex) {
}
};
while(true) {
try{
if(c.getReadyState()!= ReadyState.OPEN) {
if(c.getReadyState()== ReadyState.NOT_YET_CONNECTED) {
if(c.isClosed()) {
System.err.println("连接关闭,正在重新连接中……");
c.reconnect();
}else{
System.err.println("建立连接中……");
c.connect();
}
}else if( c.getReadyState() == ReadyState.CLOSED){
System.err.println("连接关闭,正在重新连接中……");
c.reconnect();
}
}
}catch(Exception e) {
System.err.println("连接异常,正在重新连接中……");
c.reconnect();
e.printStackTrace();
}
Thread.sleep(1000);
}
}
}