Jump to content

Dream Server


dreameo

Recommended Posts

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
Link to comment
Share on other sites

  • 2 months later...

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());
    }

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

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