我有一个客户端 - 服务器应用程序,Java SE和简单的JDBC。关于设计我的应用程序,我有一个疑问。我有以下服务器代码:
>>> from itertools import product
>>> for tup in product([32, 0], [4, 0], [1, 0]):
print('%2d = sum(%r) = sum(%r)' % (sum(tup), [format(x, '08b') for x in tup], list(tup)))
37 = sum(['00100000', '00000100', '00000001']) = sum([32, 4, 1])
36 = sum(['00100000', '00000100', '00000000']) = sum([32, 4, 0])
33 = sum(['00100000', '00000000', '00000001']) = sum([32, 0, 1])
32 = sum(['00100000', '00000000', '00000000']) = sum([32, 0, 0])
5 = sum(['00000000', '00000100', '00000001']) = sum([0, 4, 1])
4 = sum(['00000000', '00000100', '00000000']) = sum([0, 4, 0])
1 = sum(['00000000', '00000000', '00000001']) = sum([0, 0, 1])
0 = sum(['00000000', '00000000', '00000000']) = sum([0, 0, 0])
在上面的代码中,我有一个最多10个线程的执行程序服务。以前在execute方法中,当客户端连接时,我为此客户端传递新的Thread。像这样的例子:
public void runServer() throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
try (BufferedReader bufferedReader = new BufferedReader(new FileReader("configuration\\server-settings.txt"))) {
serverSocket = new ServerSocket(Integer.parseInt(bufferedReader.readLine()));
while (run) {
Socket clientSocket = serverSocket.accept();
executorService.execute(new WorkerRunnable(clientSocket));
}
} finally {
executorService.shutdown();
closeServerSocket();
}
}
但我认为这是个坏主意,因为我保持与客户端的连接,并且我最多只能同时连接10个客户端到我的应用程序。 我的客户端应用程序启动时,只调用一次连接方法到服务器:
- public void run() {
- try (ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
- ObjectInputStream ois = new ObjectInputStream(socket.getInputStream())) {
- while (true) {
- try {
- sendObject = (BaseSendObject) ois.readObject();
- command = sendObject.getCommand();
- action.invoke(sendObject, oos);
- } catch (ClassNotFoundException | IOException | SQLException e) {
- LOGGER.error("Application error", e);
- }
- }
- } catch (IOException ex) {
- LOGGER.error("Error while creating server", ex);
- }
- }
在重构代码之后,我在我的服务器中的WorkerRunnable中编写了这个run方法:
Socket socket = new Socket(server, Integer.parseInt(port));
我只处理一个客户端请求并关闭与此客户端的连接。在这种情况下,我没有在while循环中保持与一个客户端的连接。但在这种情况下,我的客户端必须始终在向服务器发送信息之前重新建立与服务器的连接:
public void run() {
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
invokeActionStrategy(objectOutputStream, objectInputStream);
socket.close();
} catch (IOException ex) {
LOGGER.error("Error while creating server", ex);
}
}
但我现在不是客户端服务器应用程序的这个好设计吗?
什么方法最好?也许其他方案?如果您有更好的示例或解决方案,请在本主题中进行说明。