Java客户端调用Websocket服务端(Springboot)
import com.sinosoft.springbootplus.lft.business.dispatch.map.application.service.impl.LawEnforceSosServiceImpl;
import com.sinosoft.springbootplus.lft.business.dispatch.map.dto.LawEnforceSosAddDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import java.nio.ByteBuffer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@ClientEndpoint
@Component
@Slf4j
public class WebSocketClient {
private static LawEnforceSosServiceImpl lawEnforceSosService;
@Autowired
public void setLawEnforceSosServiceImpl(LawEnforceSosServiceImpl enforceSosService) {
lawEnforceSosService = enforceSosService;
}
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to server");
log.info("websocket链接打开!Connected to server");
try {
String message = "你好";
// Send a text message to the server
session.getBasicRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
@OnMessage
public void onMessage(String message) throws ParseException {
log.info("收到的消息");
}
@OnMessage
public void binaryMessage(Session session, ByteBuffer msg) {
log.info("收到的消息");
}
@OnMessage
public void pongMessage(Session session, PongMessage msg) {
log.info("收到的消息");
}
@OnClose
public void onClose() {
log.info("websocket链接关闭!Close to server");
}
// ...
}