平时我们使用webSocket,一般都是浏览器作为客户端,java后端充当服务端,后端推送数据给前端,用于消息推送。这里说明的是另一种情况,一个服务端作为webSocket的server,另一个java服务端作为webSocket的client,这里面也有消息推送,不过是从一个服务推送到另一个服务,这里面没有前端什么事。话不多说,马上开始吧。
首先引入webSocket相关的pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.5</version>
</dependency>
java代码:
import com.alibaba.fastjson.JSONObject;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
@Component
public class MyWebSocketClient implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);
private WebSocketClient client;
public MyWebSocketClient() { }
@Override
public void afterPropertiesSet() throws Exception {
createClient();
}
public void createClient(){
try {
client = new WebSocketClient(new URI(url),new Draft_6455()) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
logger.info("连接成功");
//可以向webSocket server发送消息
client.send(xxxx);
}
//接收消息
@Override
public void onMessage(String msg) {
if(null!=msg&&!msg.trim().equals("")){
if(msg.equals("over")){
client.close();
}
try {
//对消息做业务处理
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void onClose(int i, String s, boolean b) {
logger.info("连接已关闭");
}
@Override
public void onError(Exception e){
logger.error("发生错误,关闭");
new MyWebSocketClient().createClient();//谨慎加这句 无限循环的可能
}
};
} catch (URISyntaxException e) {
e.printStackTrace();
}
client.connect();
while(!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)){
logger.info("正在连接");
}
}
}
网友评论