目前的效果图
最近在自己写一个netty的聊天服务器;
其中出现了一些问题,记录一下,方便回忆;
problem
花了一点时间搞定了聊天列表。但是人员退出的时候经常出现一下错误,
代码如下
public void callBack() {
String returnMsg = RedisProxy.get(ConfigConstant.chat_return_msg.getValue());
if (!StringUtil.isNullOrEmpty(returnMsg) && returnMsg.contains("{") && returnMsg.contains("}")) {
NotifyChannel notifyChannel = JSON.parseObject(returnMsg, NotifyChannel.class);
try {
/**
* 通过服务器端指定的method处理服务器端的聊天列表
*/
Method method = this.getClass().getDeclaredMethod(notifyChannel.getMethod(), NotifyChannel.class);
method.invoke(this, notifyChannel);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
} else {
chatHisId.appendText(returnMsg + "\n");
}
}
public void init(NotifyChannel notifyChannel) {
Map<String, String> chatList = notifyChannel.getChatList();
List<String> chatListView = new ArrayList<>();
for (Map.Entry<String, String> entry : chatList.entrySet()) {
chatListView.add(entry.getValue());
}
this.notifyChannel.setChatList(chatList);
ObservableList<String> strList = FXCollections.observableArrayList(chatListView);
chatHumanId.setItems(strList);
}
public void add(NotifyChannel notifyChannel) {
Map<String, String> chatList = this.notifyChannel.getChatList();
chatList.put(notifyChannel.getAddChatRemote(), notifyChannel.getAddChatPerson());
chatHumanId.getItems().add(notifyChannel.getAddChatPerson());
}
public void remove(NotifyChannel notifyChannel) {
Map<String, String> chatList = this.notifyChannel.getChatList();
chatList.remove(notifyChannel.getAddChatRemote(), notifyChannel.getAddChatPerson());
chatHumanId.getItems().remove(notifyChannel.getAddChatPerson());
}
因为javaFX只能通过javaFX的线程去更新UI,但是从报错来看,确实在javaFX线程中,莫名其妙的错误!
在stackoverflow上面找到了相关的解决方法;
How to avoid Not on FX application thread; currentThread = JavaFX Application Thread error?
Calling
Platform.runLater(new Runnable(){
// ...
});
will fix it, too.
shareimprove this answer
改动后如下:
public void add(NotifyChannel notifyChannel) {
Map<String, String> chatList = this.notifyChannel.getChatList();
chatList.put(notifyChannel.getAddChatRemote(), notifyChannel.getAddChatPerson());
Platform.runLater(() -> chatHumanId.getItems().add(notifyChannel.getAddChatPerson()));
}
public void remove(NotifyChannel notifyChannel) {
Map<String, String> chatList = this.notifyChannel.getChatList();
chatList.remove(notifyChannel.getAddChatRemote(), notifyChannel.getAddChatPerson());
Platform.runLater(() -> chatHumanId.getItems().remove(notifyChannel.getAddChatPerson()));
}
这样就不会在报错,目前项目在GitHub上,待完善。
修复一些小bug,并总结到别的文章中
读取文件路径问题:关于jar读取文件路径问题
在做私聊的时候发现上面的callback有根本上的问题,就是它只能回调群聊界面所使用的类,也就是说私聊的内容全部给打印到了群聊里面,让我情何以堪。就像这样:
于是乎!修改了一下类的结构。在这篇文章中:关于netty聊天的callback