我遇到了一个新问题。我正在用 Java+Swing 编写一个信使,我选择了这种方式来进行客户端与服务器的对话:
我有课程正在运行(所有代码都用于客户端)(服务器正常 - 我检查过)
public class Running {
private Socket s;
private PrintStream ps;
private BufferedReader br;
public Running(){
try{
s = new Socket(InetAddress.getLocalHost(), 8072);
ps = new PrintStream(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
} catch (UnknownHostException ex) {
System.out.println("11");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println("00");
ex.printStackTrace();
}
}
public String receiveLine(){
String ret = "";
try {
ret = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void sendLine(String s){
ps.println(s);
}
public void close(){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我主要做一个变量
run = new Running();
然后我将这个变量发送到任何地方,它似乎工作。它提供 readline 或 writeline throwgh 套接字。我可以注册用户、登录或添加联系人。
我可以打开一个 MessageFrame 向我的联系人发送消息。但是当我关闭它时,我的程序停止对服务器的消息做出正确的反应。它仅对 30-70% 的消息作出反应。我检查了 - 服务器没问题。所以问题出在 Running 或 MessageFrameListener
public class MessageFrameListener{
private MessageFrame mf;
private User us;
private Contact cn;
private Timer timer;
private Running run;
public MessageFrameListener(MessageFrame m_f, User u_s, Contact c_n, Running r_n){
run = r_n;
mf = m_f;
us = u_s;
cn = c_n;
m_f.addButtonListener(new SButtonListener());
m_f.addWinListener(new FrameListener());
timer = new Timer(500,new timerListener());
timer.start();
}
public class timerListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
SwingWorker<String,Void> sw = new SwingWorker<String,Void>(){
public String doInBackground() {
String ret = "";
ret = run.receiveLine();
return ret;
}
public void done() {
String[] results = null;
try {
results = get().split(" ");
} catch (InterruptedException
| ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if("m".equals(results[0])){
if("-1".equals(results[2]))
mf.addLine2("Error");
else{
mf.addLine2(results[3]);
}
}
}
};
sw.execute();
}
}
public class SButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String insert = mf.getInput();
if(!insert.equals("")){
String infoString = "m "+us.getName()+" "+cn.getName()+" "+insert;
run.sendLine(infoString);
mf.addLine(insert);
mf.refreshInput();
}
}
}
public class FrameListener implements WindowListener{
@Override
public void windowClosing(WindowEvent e) {
timer.stop();
timer = null;
mf.close();
}
新的消息!我开始调试。我的客户端从服务器获取消息并到达此行
mf.addLine2(results[3]);
但随后什么也没有发生!Swing 不会添加新行。
addLine2的代码:
public void addLine2(String line){
//dialogArea.append(line+"\n");
try {
if(line != ""){
String formLine = us.getName()+" ("+now()+")\n";
doc.insertString(doc.getLength(), formLine+line+"\n",st2);
}
}
catch (BadLocationException e){
e.printStackTrace();
}
}
当然行!=""; 可能是线程的一些 Swing 问题?Swing 不能处理我的请求?
瓦西里。