问题描述
我已经编写了以下代码,以创建一个具有恒定操作的简单ServerSocket,该ServerSocket在从数据库读取数据的同时向单个客户端发送命令。如果客户端退出并重新连接(始终使用不同的远程端口),服务器将继续向先前的“实例”发送命令。我如何区分当前客户端和断开连接的客户端,以确保将数据传递给他。您还能提出任何建议吗?
public class Server {
private static final String connectionUrl = "jdbc:mysql://localhost:3306/testdb?serverTimezone=Europe/Athens";
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(50001);
System.out.println("[SERVER 50001] Waiting for client connection...");
try (Connection conn = DriverManager.getConnection(connectionUrl,"test","1234")) {
String selectCommandSql = "SELECT `id`,`command` FROM `commands` WHERE (`is_sent` = 0 OR `is_sent` = NULL) LIMIT 0,1";
while (true) {
try {
Socket client = listener.accept();
System.out.println("[SERVER 50001] Connected to client: " + client.getRemoteSocketAddress());
PrintWriter out = new PrintWriter(client.getOutputStream(),true);
while (true) {
PreparedStatement ps = conn.prepareStatement(selectCommandSql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String command = rs.getString("command");
out.println(command);
String updateCommandStatusSql = "UPDATE `commands` SET `is_sent` = 1,`sent_at` = ? WHERE `id` = ?";
PreparedStatement ps2 = conn.prepareStatement(updateCommandStatusSql);
LocalDateTime now = LocalDateTime.now();
ps2.setTimestamp(1,Timestamp.valueOf(now));
ps2.setInt(2,id);
int success = ps2.executeUpdate();
if (success > 0 && command.equals("exit")) {
if (ps2 != null) ps2.close();
if (rs != null) rs.close();
if (ps != null) ps.close();
if (out != null) out.close();
client.close();
break;
}
}
if (rs != null) rs.close();
if (ps != null) ps.close();
Thread.sleep(100);
}
} catch (IOException | InterruptedException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
e.printStackTrace();
} finally {
listener.close();
System.out.println("[SERVER 50001] Server closed.");
System.exit(0);
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)