I'm writing a server/client application for school.
Every time I close the client, the server throws 'java.net.SocketException: Connection reset'. I think, I have to close the socket in the client before closing the JavaFX-window, but where? Or what do you think?
I've seen a similar question, but I don't know how to implement it correctly in my programm.
Exception:
20:05:27.132 [Thread-2] ERROR OnlineBank - java.net.BindException: Address already in use: JVM_Bind
19:51:06.580 [Thread-1] ERROR ServerHandler - java.net.SocketException: Connection reset
19:51:06.580 [Thread-2] ERROR ServerHandler - java.net.SocketException: Connection reset
MyProgramm:
private MyProgramm() {
server = new MyServer(Constants.REMOTE_PORT);
try
server.start();
} catch (ClassNotFoundException | IOException e) {
logger.error(e);
}
}
MyServer:
public void start() throws ClassNotFoundException, IOException {
try {
serverSocket = new ServerSocket(this.port);
while (true) {
Socket client = serverSocket.accept();
logger.debug(getClass().getName() + " accepts");
Thread threadHandler = new Thread(new ServerHandler(client));
threadHandler.start();
}
} finally {
if (serverSocket != null) {
serverSocket.close();
}
}
}
ServerHandler:
@Override
public void run() {
try (InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
ObjectInputStream oin = new ObjectInputStream(in);
ObjectOutputStream oos = new ObjectOutputStream(out)) {
while (true) {
try {
Object receivedObject = oin.readObject();
handleReceivedObject(oos, receivedObject);
} catch (ClassNotFoundException e) {
logger.error(e);
break;
}
}
} catch (IOException e) {
logger.error(e);
}
}
MainClient:
public class MainClient extends Application {
private static Client client;
public static void main(String[] args) {
launch(args);
try {
client = new Client();
} catch (IOException e) {
logger.error(e);
}
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("/welcome.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
@Override
public void stop() throws Exception {
super.stop();
// to avoid NullPointerException
if (Client != null && Client.getSocket() != null) {
Client.getSocket().close();
}
}
}
Client:
public class Client {
private Socket socket;
public Client(String remoteHost, int port) throws UnknownHostException, IOException {
if (getSocket() == null) {
socket = new Socket(remoteHost, port);
}
}
public Client() throws UnknownHostException, IOException {
this(Constants.REMOTE_HOST, Constants.REMOTE_PORT);
}
public Socket getSocket() {
return socket;
}
}