这是程序的客户端部分。我有这样的类,它与套接字一起使用,并且具有读取和写入服务器的方法我怎样才能创建一个事件来捕获来自服务器的消息?一些仅在 inputStream 中有消息时才执行操作的 actionListener。我试过调用 Running.receiveLine(); 的计时器 但效果很差。while(true) 的解决方案似乎也不好。
public class Running extends Thread{
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();
}
}
}