我需要我的學生項目幫助。 目前我正在使用JavaFX,MQTT和Mysql開發聊天應用程序。 我想做一個用戶列表(哪個用戶在線)每次添加ListView數據庫中的新條目
我試過這樣,一個新的用戶會通過一個特殊的主題發送消息,並且所有將「私下」訂閱這個主題它會收到消息(使用回調)並調用方法insertedMysql()和updatingList()。但不知何故,它不起作用。
這是我給的用戶名
public static void logging(String username) throws MqttException {
if(username != null && !username.isEmpty()) {
MysqlDatabase.insertingMysql(username);
window.close();
}
}
這是添加的ListView
public static void addItem(String item) {
userList.getItems().add(item);
}
這是我有(我認爲)問題的一部分
public class MysqlDatabase {
static String topic_body = "chat";;
static String topic_ext = "userList";
static MqttCallback sqlCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable thrwbl) {
}
@Override
public void messageArrived(String string, MqttMessage mm) throws Exception {
String username = new String(mm.getPayload());
System.out.println(username); // Checking
updatingList();
}
@Override
public void deliveryComplete(IMqttDeliveryToken imdt) {
}
};
public static void sqlConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println("Connected");
}
public static void mqttConnection(String username) throws MqttException {
MqttClient sqlClient = new MqttClient("tcp://iot.eclipse.org:1883", username);
sqlClient.connect();
sqlClient.subscribe(topic_body + topic_ext + "#");
sqlClient.setCallback(sqlCallback);
MqttMessage sqlMessage = new MqttMessage();
sqlMessage.setPayload((username).getBytes());
sqlClient.publish(topic_body + "userlist", sqlMessage);
}
public static void insertingMysql(String username) throws MqttException {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("INSERT INTO chat_test(username)VALUES(?)");
statement.setString(1, username);
statement.executeUpdate();
statement.close();
System.out.println("Inserted to database!");
mqttConnection(username);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
public static void updatingList() {
sqlConnection();
String host = "jdbc:mysql://localhost/test";
String user = "root";
String password = "";
try {
Connection connect = DriverManager.getConnection(host, user, password);
PreparedStatement statement = (PreparedStatement) connect.prepareStatement("SELECT * FROM chat_test");
ResultSet rs = statement.executeQuery();
while(rs.next()) {
String uName = rs.getString("username");
System.out.println("Username: " + uName);
JavaFXChat.addItem(uName);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
}
嗯,我想你通過一個特殊的主題發佈消息的方法。但有一些還是問題壽。謝謝! – Aye
您仍然需要發送一個明確的斷開消息,然後再幹淨地關閉與代理的連接,只有當客戶端丟失保持活動數據包時,LWT纔會觸發 – hardillb