Saturday 5 November 2011

Java: A Network Application (2)

Today's an early one, but also short, since I've had no sleep yet! Let's start at...well, the start. We'll want the lowest level of objects first, which is the NetworkNode itself, so we can have a Listener listen for it, and then the application to interact with it. This should be the only class I'm doing in 2 parts, the others look short, at a glance.

We're going to be using Random, which is in the Java libraries. I don't think we've used it yet, but it's fairly straightforward. Create a random object, then use the next...() method, you'll see below:



Yup, that's it right there, line 7. I named it random so it would be confusing :D
Lines 10 & 11 are so we have a way to tag messages going out, so they're uniquely identifiable, hence the name id. msgNumber is there to identify each individual message, just for display purposes, it's not really that important.

You'll notice that in lines 13-15, where we have our constructor, its tagged as private. This is simply to make sure that the only way to actually create a NetworkNode object is by using a method, which you'll see on Monday!

Lines 16-25:  This just represents the independent behavior of the Node object.All it does is send out a tagged message regularly. Sent in a random interval of 0-5 seconds. On line 19, that just reads:
sit around for an amount of time equal to [random between 0 and 5] thousand milliseconds
Without the *1000, we'd have messages every couple of milliseconds, which is a terrible strain on my crappy computer.

I don't care about exceptions in this case, so in line 20, I catch it because I have to, but won't do anything with it. You can, if you want, I guess.

Line 22-23: Notify every blocked thread that a message is available, then increment the message number.



And that's it, for today! I'm freaking tired, and if I slept first, I'd be writing this post tomorrow, which is my day off, so I think I'll go enjoy that! See you Monday!

3 comments:

  1. interesting... i've just started programming in c++ so this is relevant to my interests.

    ReplyDelete
  2. Enjoy your day off by sleeping. That's what I'd do.

    ReplyDelete