java 编写客户端以在 Spring Boot 中连接到 websocket
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29386301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing a client to connect to websocket in spring boot
提问by FusionHS
I'm trying to make a websocketed based server/client application using spring boot.
我正在尝试使用 Spring Boot 制作一个基于 websocketed 的服务器/客户端应用程序。
The server accepts a socket connection then when it recieves a text message from the client it will process it, then return some data. The server has a websocket handler that will correctly process a request.
服务器接受一个套接字连接,然后当它收到来自客户端的文本消息时,它将处理它,然后返回一些数据。服务器有一个 websocket 处理程序,可以正确处理请求。
public class DataWebSocketHandler extends TextWebSocketHandler {
private static Logger logger = LoggerFactory.getLogger(DataWebSocketHandler.class);
private final DataService dataService;
@Autowired
public DataWebSocketHandler(DataService dataService) {
this.dataService = dataService;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) {
logger.debug("Opened new session in instance " + this);
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
byte[] payload = this.dataService.getDataBytes(message.getPayload());
session.sendMessage(new BinaryMessage(payload));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception)
throws Exception {
session.close(CloseStatus.SERVER_ERROR);
}
}
and registered
并注册
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(dataWebSocketHandler(), "/data").withSockJS();
}
My problem is, is that I have no idea how to write a client that can connect to the server(assuming I wrote the server correctly) and by extensions how to send the message and how to receive that data on the client side.
我的问题是,我不知道如何编写可以连接到服务器的客户端(假设我正确编写了服务器)以及扩展如何发送消息以及如何在客户端接收该数据。
I've failed to find an example of this, but there are plenty where a websocket is written that broadcasts to all clients subscribed to a socket, which I don't want.
我没有找到这样的例子,但是有很多地方写了一个 websocket,它向所有订阅了套接字的客户端广播,这是我不想要的。
The server uses the embeded tomcat server.
服务器使用嵌入式tomcat服务器。
采纳答案by Gokhan Oner
I believe this is what you're looking for
我相信这就是你要找的
this is a similar server side code..
这是一个类似的服务器端代码..
And here is the client side.. using org.springframework.web.socket.client.standard.StandardWebSocketClient ad some othe configuration.
这是客户端..使用 org.springframework.web.socket.client.standard.StandardWebSocketClient 和一些其他配置。
I believe you can figure out the rest ;)
我相信你可以弄清楚其余的;)
Cheers
干杯