0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
sonti yo
  • 61
  • 1
  • 9
  • 2
    The server only accepts one connection and reads one line, then it exits. You need a loop. You also need to read the custom Networking section of the Java Tutorial. – user207421 Jun 18 '18 at 21:58
  • I will look right into it. Thank you for the directions! – sonti yo Jun 18 '18 at 22:06

0 Answers0