Java client/server

Flayed

Senior member
Nov 30, 2016
431
102
86
Hello, I'm writing a simple multithreaded java client/server program for a college assignment. There's lots of example code online and in books which is great.

The problem I'm having is that my teacher doesn't want me to use inner classes for either the GUI event handlers or for the threads. All the example code I've seen uses inner classes for these things.

I'm trying to think of the best way to overcome this restriction. So far all I've come up with is in the server code when the server creates a new thread to service the client, to pass in as arguments to the ClientHandler thread the variables needed.
However now I'm thinking the client thread needs to broadcast a message to all connected clients this will be a method in the server class so i need to pass in a reference to the server instance into each client thread using the this keyword? Its just this doesn't seem like a very good solution.

The other idea I had was to use the Observer and Observable design pattern but this was for the client Thread to indicate to the server that it needs to be removed from the list of connected clients and if i use it to do that i don't think i can also use it to indicate that a message needs to be broadcast.

Plus if i'm passing in a reference to the server i can just have the client remove itself from the list.
 

Cogman

Lifer
Sep 19, 2000
10,284
138
106
TBH, not being able to use inner classes is a silly and dumb restriction. Inner classes are the lifeblood of GUI work in java. You can get around this by making new handler classes outside of the parent class and even passing the parent class into those handler classes when needed.

Some of the tutorial's might not be updated, if the interface into the method has only one method on it, then it is possible to use lambdas which aren't technically inner classes (That is how you could get around some of the restrictions there).

I guess it depends on what is wanted in the assignment. One thread per connection is easy to do, but slow and resource intensive, but the early internet was pretty much that model. A more efficient model is doing connection handling on the thread pool. The best model is going to be the asynchronous socket model combined with a thread pool sized to the number of cores on the box. You can see a demo of how to do that here.

https://www.ibm.com/developerworks/library/j-nio2-1/

If your application is supposed to be a HTTP server, then I suggest an entirely different approach. But if you are doing something more low level then this is probably the way to go.

If you want a more high level setup, then I suggest looking into Akka. Another option is Hazelcast.

As far as layout goes, I would suggest not going P2P if you can avoid it and instead only connect clients to the server. If something needs broadcasting, I suggest that the server handles that.