[英]synchronize between multiple clients in a server
I have a Server that can receive multiple request at the same time.我有一个可以同时接收多个请求的服务器。
In my Server, I have to make some traitement and wait for response.在我的服务器中,我必须做一些特性并等待响应。 This traitm.net is done by externe library so I don't how much should I wait.
这个 traitm.net 是由 externe 图书馆完成的,所以我不知道我应该等待多少。
So the Server looks like:所以服务器看起来像:
public class MyServer{
@Override
//method from the library
public void workonRequest(){
//---
response=[...]
}
public void listenRequest() {
new Thread(() -> {
while (true) {
try {
socket = server.accept();
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
socket.setTcpNoDelay(true); //TODO : Not sure !
new Thread(() -> {
try {
handleRequest(input, output);
} catch (IOException e) {
throw new RuntimeException(e);
}
}).start();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}).start();
}
And the handle request method is:处理请求方法是:
public void handleRequest(ObjectInputStream input, ObjectOutputStream output) throws IOException {
try {
while (true) {
//forward the request to the library
//work on it [means using the library and waiting]
// return response
}
}
}
The response object is the result that I want return to the client响应object是我要返回给客户端的结果
Thanks in advance提前致谢
Using while(true) can create issues because you are blocking the thread and opening sub thread and multi streams will make it more complex.使用while(true)会产生问题,因为您正在阻塞线程并打开子线程和多流会使它变得更加复杂。 There is easy way called reactive programming which handles this kind of multi-threaded issues easily, quarkus async solution and spring , if you still want to manage your sockets from java code you can use akka
有一种称为反应式编程的简单方法可以轻松处理此类多线程问题, quarkus 异步解决方案和spring ,如果您仍想从 java 代码管理您的 sockets,您可以使用akka
That can be done by not blocking the main thread and If you manage to use reactive and/or async approach you will not have that problem.这可以通过不阻塞主线程来完成,如果您设法使用反应式和/或异步方法,您将不会遇到这个问题。
Reference参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.