Network: Code review - Detecting Client() timeout and behaving well during connection process
in
Core Library Questions
•
2 months ago
I've built a simple little network system based on Server and Client.
I can't always control when the parts start so I'm trying to make the connection process as smooth as possible.
I'd like to be able have the client start first and then cleanly pick up when the server starts. It needs to retry a connection, or at least handle the timeout cleanly. And I like to be able to stop the app early if I change my mind and decide to not to start.
The server side works fine with nothing special. The app is responsive works as expected while waiting for a client to connect. The client side seems to block until it either times out or connects. During the client's timeout period the app is not responsive and can't be quit early if the user decides to give up. Finally if it does timeout there isn't a direct way to detect that it timed out.
I eventually built a bit of code that does works to some level. I have a simple state machine in draw() that works through a couple startup states.
- println("waiting for server");
- // there's also a text() here expleining this to user.
- boolean gotNetwork = true;
- myClient = new Client(this, "127.0.0.1", 21015);
- try {
- String tmp = myClient.ip();
- }
- // it appears there is no direct way to detect a successful connection.
- // However Client.ip() will throw a NullPointException when it's not connected.
- catch (java.lang.NullPointerException e) {
- gotNetwork = false;
- }
- if (gotNetwork) {
- initStage++; // controls my draw statemachine. incrementing moves to next state
- }
Any thoughts on how I'm pulling this off? Suggestions on a better a way to do either of these things?
1