Download code here

This is the third post in the series which I am writing about network programming in a few different languages and frameworks.  In this post I will be creating the base send and receive you would expect to see from the basic client server model.  I have left the send parameter as a byte array as in future posts I will be creating different handlers for different types of messages being sent.  In up coming posts I want to make a client which can be server agnostic and simply rely on the sub net to pulse for accepting clients.  For now though, I have created a simple, working example of a client server environment.

image

Earlier posts I have done in this series can be found below:

  1. Part 1 : Socket Programming with C#, JAVA, C++ and Action Script 3.0 – Establishing a base connection and communication with C# Server and AS3
  2. Part 2 : Socket Programming With C#, JAVA, C++ and Action Script 3.0 – WCF : Establishing a call-back for use in a client server environment

In the first post in the series I did touch slightly on establishing a socket connection with Action Script 3 so this post will bring a third language to the table being Java.  In the second post, I was still using C# but together with the Windows Communication Foundation and the NetTcpBinding.

For this example also, I have put together another simple implementation of the Model View Presenter for the user interface.  I wanted the view and the model to be ignorant of any implementing classes.  Both emit events and both are known to the presenter.

NetBeans

The environment I have used to dev this example is NetBeans IDE which I have to say I really like.  On a day to day basis I work with Visual Studio, which I also feel is a great IDE but I would seriously have to sit down and have a good think to decide which I preferred. One of the tools which I have used is the UML plugin, which after I had prototyped, built, went back to the drawing board, repeated and built again, I used to reverse engineer the project and provide a nice UML Class Diagram with.  Below is the classes which are responsible for the network communication and underneath that, the diagram displaying the user interface code.

The Network Communication Classes

Net

The User Interfaces Classes

Main

The Event Model in Java

Slightly different in its implementation from C# the Java Event Model relies on the creation of interfaces which define events that a subscriber of events has to implement if it wants to be notified by the object which raises such events.  The way it would raise any event is simply looping through the subscribers and invoking the method on it, which it can safely do so as it will identify the subscribers by its contract/interface.

For example, in the network communication classes above, I have a Receiver object and this can raise two types of events being:

  • When it receives data
  • When it loses the connection due to the remote connection being closed.

So with this in mind I need to create an interface which will provide me with this assurance.

public interface IReceiverEventListener extends EventListener {
    void onDataReceived(byte[] data);
    void onConnectionLost();
}

Another note which I should bring up here is that I implement this interface on both the subscriber and the class which emits the event.  I could have created a separate interface I suppose call IReceiverEventInvoker – but the difference is that the class which raises the events will use the above methods to loop through its subscribers and invoke the method on them, the subscribers will use the above method to actually handle the event.  To the class which raises the event, this method is like a proxy to all the other subscriber events.  Here is how the implementation of the onDataReceieved method looks like on the class which raises the events.

    public void onDataReceived(byte[] data) {
        for(IReceiverEventListener listener : _listeners.getListeners(IReceiverEventListener.class)){
            listener.onDataReceived(data);
        }
    }

Blocking and Looping

Although in my first post with the C# example, I have not used any while loops, and instead gone with the asynchronous programming model, under the covers, it will be doing that very thing, as you have to maintain a connection to an endpoint in order to communicate with it.  In this code on both the server and the client code I have used a while loop to continually listen for connecting clients and also for the client to continually listen for incoming data from the server. 

The blocking comes from the the call to the read method on the InputStream.  While there is data to read the while loop allows the process to continue until it has read all of the incoming data, and when finished the while loop again allows the read method to be called and block until it is ready to read again.

The following is the Receiver class which I have created as I need the receiving of data on a client to be done on a separate thread, so I can handle other functions like sending data without worrying about blocking or waiting for each other.

public class Receiver implements Runnable, IReceiverEventListener {

    private Socket _socket;
    private BufferedInputStream _inputStream;
    private ByteOutputStream _stream;
    private EventListenerList _listeners;

    public Receiver(Socket socket) throws IOException{
        _socket = socket;
        _inputStream = new BufferedInputStream(_socket.getInputStream());
        _listeners = new EventListenerList();
    }

    public void run() {
        while(true){
            try {
                byte[] buffer = new byte[1024];
                int read = 0;
                read = _inputStream.read(buffer, 0, 1024);

                _stream = new ByteOutputStream();

                if(read == -1){
                    onConnectionLost();
                }else if(read < 1024){
                    _stream.write(buffer, 0, read);
                    onDataReceived(_stream.toByteArray());
                    
                }else{
                    _stream.write(buffer, 0, read);
                }

            } catch (IOException ex) {
                Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void onDataReceived(byte[] data) {
        for(IReceiverEventListener listener : _listeners.getListeners(IReceiverEventListener.class)){
            listener.onDataReceived(data);
        }
    }

    public void onConnectionLost() {
        for(IReceiverEventListener listener : _listeners.getListeners(IReceiverEventListener.class)){
            listener.onConnectionLost();
        }
    }

    public void addEventListener(IReceiverEventListener listener){
        _listeners.add(IReceiverEventListener.class,listener);
    }

    public void removeEventListener(IReceiverEventListener listener){
        _listeners.remove(IReceiverEventListener.class,listener);
    }

}
In the above code, specifically inside the while loop, there are three outcomes which I am interested in:

  1. If the connection has ended between the client and server
  2. If the final piece of the data is being read
  3. If the data read is part of the entire transmission

As I collect the data I write it to an output stream so at the end of the transmission I can then trigger events with the entire data received.  I have made a buffer of 1024 in length, just for the purposes of example.  There is a balance to be had on the amount of data to be sent and the bandwidth available to send it on.

The implementing class of this receiver is the Client class, which when started will kick off the Receiver in a separate thread, first having added itself to its listeners, so it can act of data being received or the connection being lost.  This class has two uses, the first being that it will be used by clients to connect to a server and the second is that when the server accepts a connection it will create an instance of this class on a separate thread to represent the client and enable communication between it and the client.

public class Client implements Runnable, IReceiverEventListener, IClientEventListener {

    private String _ip;
    private int _port;
    private Socket _connection;
    private Receiver _receiver;
    private EventListenerList _listeners;
    private String _name = "Server Client";

    public void set_Name(String value)
    {
        _name = value;
    }

    public String get_Name(){
        return _name;
    }

    public Client(Socket connection) {
        this(connection.getInetAddress().getHostAddress(),
                connection.getPort());
        _connection = connection;
    }

    public Client(String ip, int port) {
        _ip = ip;
        _port = port;
        _listeners = new EventListenerList();
    }

    public void run() {
        try {

            System.out.println("Client started");

            if (_connection == null || !_connection.isConnected()) {
                _connection = new Socket();
                _connection.connect(new InetSocketAddress(_ip, _port));
            }

            _receiver = new Receiver(_connection);
            _receiver.addEventListener(this);
            new Thread(_receiver).start();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onDataReceived(byte[] data) {
        onClientDataReceived(data);
    }

    public void onConnectionLost() {
        onClientDisconnected(this);
    }

    public void addEventListener(IClientEventListener listener){
        _listeners.add(IClientEventListener.class,listener);
    }

    public void removeEventListener(IClientEventListener listener){
        _listeners.add(IClientEventListener.class,listener);
    }

    public void onClientDataReceived(byte[] data) {
        for(IClientEventListener listener : _listeners.getListeners(IClientEventListener.class)){
            listener.onClientDataReceived(data);
        }
    }

    public void onClientDisconnected(Client client) {
        for(IClientEventListener listener : _listeners.getListeners(IClientEventListener.class)){
            listener.onClientDisconnected(client);
        }
    }

    public void Send(byte[] data){
        try {
            _connection.getOutputStream().write(data, 0, data.length);
            _connection.getOutputStream().flush();
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

The entire code set can be downloaded from the link above.  At present all this application can do is receive connections and data from clients and transmit that data to all other connected clients.

The server code shown below, is what handles the client connection and also the distribution of the message to the other connected clients.  This is very early stages, so there are many more things I want to add to this, but I thought I would get a nice example of a client server application up for both my own benefit and hopefully so it can help any one else out there.

public class Server implements IClientEventListener, Runnable {

    private ServerSocket _socket;
    private ArrayList<Client> _clients;
    private int _port;

    public Server(){
        _clients = new ArrayList<Client>();
    }

    public void listen(int port) throws IOException{
            _port = port;
            new Thread(this).start();
    }

    public void onClientDataReceived(byte[] data) {
        for(Client client : _clients){
            client.Send(data);
        }
    }

    public void onClientDisconnected(Client client) {
        System.out.println("Client disconnected");
    }

    public void run() {
        try {
            System.out.println("Listening");
            _socket = new ServerSocket();
            _socket.bind(new InetSocketAddress(_port));
            while (true) {
                Socket clientSocket = _socket.accept();
                Client newClient = new Client(clientSocket);
                newClient.addEventListener(this);
                _clients.add(newClient);
                new Thread(newClient).start();
            }
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Finally for the purposes of this demo I wanted a simple interface for the chat client and similar to popular IM programs now, I simply need a text area to type into, a text area to display messages and a button to send.  Like I have said above though I wanted the view to be ignorant of anything outside of it, so the interfaces to the presenter and the view are shown below.

public interface IChatClientPresenter {
    void setView(IChatClientView view);
    void handleChatSent();
    void handleChatReceived(byte[] data);
}

The actual view interface.

public interface IChatClientView{
    void addChat(String text, String from);
    void addChatListener(IChatEventListener listener);
    void removeChatListener(IChatEventListener listener);
    String getChatText();
    void clearChatText();
}

The listener interface for the client. 

public interface IChatEventListener extends EventListener {
    void onChatSent();
}

Extensibility and Transport

To take this to the next level I want to be able to add attributed data to the data sent, in a way wrapping the data into custom containers and chunking the transmission.  If we think about extensibility and passing information around to multiple types of clients, we could immediately think of web services.  So along this line I want to use SOAP as the container and send these.  This will allow me to create custom message classes and extend each with different handlers and confidently send these across the wire and may be create handlers for the messages which the receiving client will resolve upon de-serialization.  If the message cannot be de-serialized then it can simply fall through to a default handler. 

So to the next post in the series and hopefully in a few more maybe a client working on a similar basis for the android platform.

Cheers for now,

Andrew


Wednesday, October 21, 2009 12:40:00 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer

A comparison with other languages to .NET during my programming experiences.

I like to bring a .NET programming naming convention to my other programming in different languages e.g. parameters, local variables, interfaces, functions etc...

Of late I am programming in Java more and more, as an accompaniment to my current programming skill set and by no means a substitution.  What I mean is that I am offering Java now as one of my skill set, if it fits a clients specification, so in essence giving me more tools and the client more options.

I would like to point out one observation though from the outset. 

As my background is from .NET and Microsoft managed languages, I am constantly making adhoc comparisons, judgements, evaluations etc... between the two.

  • Hmmm I like that idea, or
  • Nah that's good but I prefer the way they do it in ... or
  • Hey that's cool, both have opted to go they same way on that one!

So basically my likes, dislikes, wants, unknowns and general observations of equality. so below I have grouped a few observations so far.

Interfaces

I definitely prefer to prefix my interfaces with the uppercase I, i.e. IMyInterface as opposed to simply MyInterface.  So when I am coding I use the I prefix for my interfaces, as I like the immediate and obvious differentiation between an interface and class object.

In Java you have to specify public scope for your methods, where as in C# this is not allowed and it is presumed that the coder understands any methods WILL BE public.  I am on the fence on this one as I can see benefits for both.

Properties

I like the getter and setter convention in C#, including the new shortcuts in .NET 3.5 which describe properties, e.g.

public string MyProperty{get;set;}

or

public string MyProperty{
	get{return myProperty;}
	set{myProperty = value;}
}

Method Overloading

This is a like I had from ActionScript, and one which I have read WILL be implemented in C# 4.0, and I am not sure of its name but i call it Dynamic Method Overloading.  In ActionScript you are able to provide the paramaters of a method's signature with default values.  So for example say you have ONE method with TWO parameters and the second one having a default parameter e.g.

public int MyMethod(int firstArg, int secondArg = 2)
{
	Add(firstArgs,secondArg);
}

I could then call this function like so:

int value1 = MyMethod(10); //Result would be 12
int value2 = MyMethod(10,10) //Result would be 20

So you can see in the first invocation I only supply one parameter, yet what is returned is the first parameter and also the second parameter added together as per the method's instruction.

Namespace Import

This is not a like or dislike but rather an observation of dissimilarity.  If I want to import all classes from the System.Net namespace inside .NET I can do just that by saying using System.Net yet in Java I must suffix with an asterisk, and one of the reason I can understand as to the reason is that you can import single classes as opposed to their namespace or package. For example I could specify an import for a JCheckBox itself in Java i.e.

import javax.swing.JCheckBox;

I could not do the same in C#, for example the following is not correct:

using System.Net.Sockets.Socket;

Again I neither like or dislike both of them but I think the difference is ironically large and small at the same time.

Event Model

I will be publishing a post about this topic individually in which I will describe events using a model a showing the relevant counterparts of C#, Java and ActionScript.  I have not yet got the knowledge to produce a C++ example so if anyone reading could and kindly would not mind, I would greatly appreciate the input.

Each of the following are what I feel I need to focus on in the blog post for each language by way of how they implement an Observer Pattern or Events.

In Java there are a the following to focus on which have slightly different uses but ultimately for the same purpose which is notification of change or action.

  • Observer
  • Observerable
  • EventObject
  • EventListener

In C# I need to focus on:

  • Delegates
  • EventHandlers
  • Event
  • Chaining Invocation

In ActionScript I would focus on:

  • The Event Object
  • The IEventDispatcher Interface

I will use an example for the above languages and a few events a car emits which will show the different implementations of the above.

Class Naming Conventions

Both Java and ActionScript require the name of the file to equal the name of the class.  C# on the other hand does not have this requirement.  I would assume that this is because in C# I am able to put more than one class in a .cs file, and by that I do not mean nesting.  In Java and ActionScript I can nest classes inside others but I cannot start a new class declaration in the same file after one has already been declared.  Personally I agree with the Java implementation and would like to see each class in its own file if not required to nest.

That being said though I think that Partial Classes in .NET are such a good IDEA and a great piece of architectural planning and implementation.

Tis all for now lol.



ActionScript | C# | Java
Tuesday, January 27, 2009 10:56:48 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer

I am currently inside the NetBeans IDE which is my IDE of choice at the moment for my Java development.  I thought I would mention a refactoring feature I would like to see inside Visual Studio "Out of the Box."  It is with regards to the encapsulation of fields. 

  • Yes you can create a class diagram and encapsulate a field
  • Yes you can right click in code view and encapsulate a field
  • Yes you can download, purchase or create a plug in to do the following

BUT, I would like to see two things:

  1. The following functionality out of the box ready
  2. The ability to encapsulate a selection of fields or to be able to select the fields you would like to encapsulate inside a nice GUI Dialogue.

Some may say lazy, others may say more productive.  In NetBeans I can go to the refactor menu and click encapsulate fields and I am presented with a nice dialogue where I can select the fields I would like to encapsulate and also a few more properties to describe the encapsulation I desire for each field.  Just saves time in my view.

image

I am greedy lol, what I would also like to see form the NetBeans dialogue above is also to open it up after refactoring and being able to edit.  That would be really useful.  I am going to download Visual Studio 2010 and see what is new and going on lol.  It can be found here:

http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&displaylang=en

Cheers,

Andrew



C# | Java
Saturday, January 17, 2009 12:59:22 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer

I have just been playing around making a small networking application using Java when i came across a small and dead simple function which I thought, "hey that is useful," and "oh that would now fit .NET Extension Methods."  So straight away lol and got my console up and had a play, and i know it may seem a bit trivial, but it is just a bit tidier than other methods you could use.  In all I just like the simple function of the .... function.  Working in a case sensitive language, it seems quite relevant to differentiate.

Anyway, enough blabbering, the function is called equalsIgnoreCase(String inValue) and to use in C# simply create a string extension method like so, with an implementation following:

    public static class StringExtensions
    {
        public static bool EqualsIgnoreCase(this string value, string compare)
        {
            return (compare.ToLower() == value.ToLower());
        }
    }

            Console.WriteLine("QuIt".EqualsIgnoreCase("quit"));

The output is True obviously :-)

Cheers,

Andrew



C# | Java
Friday, January 16, 2009 5:46:47 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer