【发布时间】:2019-09-17 20:54:42
【问题描述】:
我将创建一个与 REST API 服务器通信的客户端,该服务器由 Spring 框架提供支持。在某些情况下,我想从客户端->服务器发送数据,服务器应尽快回复,然后我将从客户端->服务器发送数据,服务器从服务器->客户端发送数据尽快尽可能。重复它,直到客户端的用户不再发回数据。
我想我可以在 Spring 中使用 REST API 来做到这一点,但有没有更好的方法?我的意思是更快的发送数据的方式?或者,只要我在服务器和客户端之间有良好的通信,REST API 就足够快了?
我正在使用 Apache HTTPD 库与 Spring REST API 对话。有用。下面是我连接 REST API 和登录的示例。
try {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(serverAddress.getText(), Integer.parseInt(serverPort.getSelectedItem().getText())), new UsernamePasswordCredentials(userName.getText(), password.getText()));
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
connections.setHttpclient(httpclient);
HttpGet httpget = new HttpGet("http://" + serverAddress.getText() + ":" + serverPort.getSelectedItem().getText() + "/user/connect?username=" + userName.getText());
CloseableHttpResponse response = httpclient.execute(httpget);
String entity = EntityUtils.toString(response.getEntity());
if (entity.equals("connected") == true) {
connectServerButton.setText("Disconnect from the server");
dialogs.alertDialog(AlertType.INFORMATION, "Connected", "You are now connected");
connections.setConnected(true);
connections.setServerAddress(serverAddress.getText());
connections.setServerPort(serverPort.getSelectedItem().getText());
connections.setUserName(userName.getText());
response.close();
} else {
dialogs.alertDialog(AlertType.ERROR, "Not connected", "Failed to login");
}
} catch (IOException e) {
dialogs.exception("Cannot connect server", e);
}
控制器是
@GetMapping("/connect")
public String connect(@RequestParam("username") String username) {
// This will connect the user
User user = userRepository.findByUsername(username);
if(user == null)
return "disconnected";
// Set some values
Online online = onlineRepository.findByUsername(username);
online.setOnline_id(user.getUser_id());
online.setOnline(false);
online.setDevice("-");
onlineRepository.save(online);
return "connected";
}
这就是我连接 REST API 并与之对话的方式。如果我想要更快的沟通,你有更好的方法吗?我并不是说我要求全双工。那会很好,但不是必需的。我要求的是服务器的快速响应。
如果服务器可以在 10 毫秒内响应(自己的 LAN 网络、快速计算机、快速 DHCP 服务器),我会很高兴。我不发送大数据,只发送小字符串。
【问题讨论】:
-
你可以考虑 websockets 或 gRPC
-
@MartinVanWingerden 我不能做网络套接字,因为客户端是一个 Android 应用程序。
-
GPRC 听起来是个好主意!你认为我可以将它与 Spring REST API 结合起来吗? :)
-
@DanielMårtensson 你可以为 Android 开发 WebSockets
标签: java spring rest spring-boot