问题
私聊的callback成了这个样子,在《写netty聊天出现的问题》中提到了这个问题,不管怎样,这必须得解决啊!
代码
先看看之前的代码:
1
public void initRootLayout(String host, int port) {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(this.getClass().getClassLoader().getResource("root.fxml"));
try {
AnchorPane load = loader.load();
RootLayoutController rootLayoutController = loader.getController();
intClient(host, port);
rootLayoutController.setClient(client);
rootLayoutController.setAppMain(this);
/**
* 控制回调
*/
client.setRootLayoutCallBack(rootLayoutController);
Scene scene = new Scene(load);
primaryStage.setTitle("Chat");
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
2
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 (Exception e) {
e.printStackTrace();
}
} else {
chatHisId.appendText(returnMsg + "\n");
}
}
这样的结果就是上图所描述的,回调永远都走这个代码;
解决
首先确定回调的代码是运行的时候才回调的,所有先将callback这个方法拿出来创建一个abstarct父类 LayoutController
提取到父类,像这样:
public abstract class LayoutController {
public abstract void callBack();
}
让所有需要回调的layout继承这个类,修改netty client类所需要回调的类的类型为LayoutController;它运行的时候其实是具体的子类。
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
private Logger logger = LoggerFactory.getLogger(ChatClientHandler.class);
/**
* 回调rootLayout
*/
private LayoutController layoutController;
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
RedisProxy.set(ConfigConstant.chat_return_msg.getValue(), s);
layoutController.callBack();
logger.debug(s);
}
public void setLayoutController(LayoutController layoutController) {
this.layoutController = layoutController;
}
}
LayoutController整理后变成入口。
public abstract class LayoutController {
protected Logger logger = LoggerFactory.getLogger(this.getClass());
protected ChatClient client;
protected Main appMain;
protected String remoteAddr;
protected String remoteName;
public abstract void callBack();
public void setClient(ChatClient client) {
this.client = client;
}
public void setAppMain(Main appMain) {
this.appMain = appMain;
}
public void setRemoteAddr(String remoteAddr) {
this.remoteAddr = remoteAddr;
}
public void setRemoteName(String remoteName) {
this.remoteName = remoteName;
}
}
现在如果一个人点击私聊,另外一个人并没有私聊的界面,依然会在群聊界面里,所以在服务端添加规则,让开启私聊的对象所指定的对象开启私聊界面。