-1

So basically I'm doing a server and client in java.

In order for it to run, I have to run both a client.java and server.java. I need to close one or both depending on the instance

What I currently need is a way such that when the client passes a parameter x, the client should close but the server should remain open. I also have to implement it in such a way that if client passes parameter y instead, both the client and server should close

I thought of doing:

System.exit(0);

But I'm not sure if this would close both server and client, meaning that it would be useful for the second instance. I also thought of just letting it reach the end of the program, but I'm not really sure what result would be the result of that.

steve
  • 13
  • 3
  • The question is rather ambiguous. With client server connections, when the client is closing, it would ideally terminate the connection to the server then close itself. The server program shouldn't be effected by if the client shuts down intentionally or unintentionally. Given that these should be separate Java programs. – avlec Feb 18 '18 at 04:37
  • If, the client and server are running in their own JVMs, then using `System.exit(0)` in one won't stop the other – MadProgrammer Feb 18 '18 at 04:42

1 Answers1

1

If you want the server to keep listening for more requests for a handshake (even when previous connections terminate), what you need is a multi-client server. A server that can handle multiple clients usually runs a thread that keeps looping and listens for a client that wants to connect. Such a thread would generate a new thread for each connection and store it in an array of threads that all keep listening or talking with each client.

You can learn more about multiple client servers here.

With the array of threads listening to all clients, you could assign a condition that terminates all threads and connections in the server. This could be a String that one of the clients can relay to the server, such as "/exit" and the server can check if information sent by any client-thread is "/exit".

JYun
  • 311
  • 2
  • 12