I'm creating a NetUtils class which extends thread to handle socket communications in a GUI without blocking the main thread. My code looks like the following (assume all import are accounted for):
Main method
public static void main(String[] args) {
EventQueue.invokeLater( () -> {
new Window().setVisible(true);
});
}
Window class
public class Window { // normally would extend JFrame bc this is a gui
// ...
NetUtils comms;
public Window() {
// ...
comms = new NetUtils("192.168.1.1", 288); // this ip/port info works fine
comms.start();
// ...
}
// other methods....
}
NetUtils class
public class NetUtils extends Thread {
private String ip;
private int port;
public NetUtils(String ip, int port) {
this.ip = ip;
this.port = port;
}
@Override
public void run() {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, port), 10000); // timeout 10s
System.out.println("Socket started: " + socket); // correctly prints
while (true) { // during the life of the thread
String line = readLine(socket); // throws SocketException here (socket closed error)
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String readLine(Socket socket) {
// uses inputstream to read bytes and such
String line;
boolean isDone = false;
while (!isDone) {
try (InputStreamReader isr = new InputStreamReader(socket.getInputStream))) {
if (isr.ready()) {
line += (char) isr.read();
}
if (!isr.ready() && line != "") {
isDone = true;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return line;
}
}
What am I doing that would cause the socket to close? I ran the NetUtils code directly in the main method (I didnt separate out the readLine method) and it ran as I expected it to which lead me to believe the problem has to do with the socket being in a thread. Thanks for the help.