I'm struggling with setting up my first server/client connection. My GUI has a dialog. Upon pressing a Send Button inside of that, I call client.connect().
It works the first time, but when I go ahead and reopen the dialog (it closes by itself after pressing Send) and attempt to do the same again, I will get the "connection refused" error. I suspect this is due to the server still being connected to the original socket and the Button Event triggering client.connect()
again. (Which will try to connect a new one). But I don't know how I can make sure this doesn't happen. I somehow have to close the client Socket once the dialog closes, right? How do I implement this? Or does the problem lie somewhere else? This was just a guess that feels kinda right.
Here's my Client
class (it includes the connect()
method called above):
public class Client extends Application
{
private String string = "";
Socket s;
@Override
public void start(Stage primaryStage)
{
VBox root = new VBox();
Scene scene = new Scene(root, 380, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) throws IOException
{
Client client = new Client();
client.connect();
launch(args);
}
public void connect() throws UnknownHostException, IOException
{
s = new Socket("localhost",3000);
System.out.println("Connected");
PrintWriter dos = new PrintWriter(s.getOutputStream());
dos.println(string);
dos.flush();
}
}
And here's my Server
class:
public class Server
{
public static void main(String[] args) throws UnknownHostException, IOException
{
ServerSocket server = new ServerSocket (3000);
Socket s = server.accept();
System.out.println("Connected");
BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(dis.readLine());
}
}
Please note this is my first time ever setting up Server/Client in java, hence the localhost to try it out and the probably obvious problem.