This is a client part of programm.
I have such class which works with sockets and has methods to read and write to server
How can I make an event to catch messages from server?
Some actionListener which makes actions only when thereis a message in inputStream.
I’ve tried timer which calls Running.receiveLine(); but it works very bad.
The solution with while(true) also seems to be not good.
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();
}
}
}
I think it’s not a problem to use method
read()because it blocks flow until new portion of data is available. All standard Java input streams have a good implementation of this approach, based on monitors. So your thread won’t eat CPU and other resources during waiting.Also you can refer to non-blocking IO in Java NIO.
Small addition.
To use it with
Swingyou can use queue approach in fusion withSwingWorker.