Jump to content

Dream Server


Recommended Posts

Posted

Here's a very nice and easy to use Client/Server program. You must define you're own protocol and modify the onMessage functions to then support your protocol. MessageParser.java and Message.java must be altered to reflect your protocol (such that you can extract the required data).

 

Note: Not fully tested, could be some problems. Let me know.

 

https://gist.github.com/DreamLean/61b215bad3c8f839ac4c84536d67c804

  • Like 5
  • Boge 1
  • 2 months later...
Posted

Update, been playing with this a bit more. Still working on a protocol, but in working with it I did find at least one issue. Should the server close immediately or not gracefully, this error will be repeatedly thrown from Client.onMessage as it is called regularly by the ScheduledExecutorService.

image.png.775d9d0eebb2126f65406c3579b193bb.png

I found a somewhat-OK fix through a StackOverflow answer. I pulled out the ByteBuffer operations and did a test of the exception message, which is quite messy but works.

    private void onMessage() {
        ByteBuffer inputBuffer = ByteBuffer.allocate(256);
        try {
            client.read(inputBuffer);
        } catch (IOException e) {
            // If the server was closed, the IOException will hint at this.
            // https://stackoverflow.com/questions/5638231
            if (e.getMessage().contains("An existing connection was forcibly closed by the remote host")) {
                System.out.println("Server closed, stopping.");
                close();
                return;
            }
            e.printStackTrace();
        }
        consumer.accept(new String(inputBuffer.array()).trim());
    }

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...