[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 322
  • Last Modified:

Implementing the Observable Interface

I am trying to write a simple application which works like this:  It has a server program and a client program.  The server must accept multiple connections from clients over a network.  Once connected, the clients have a simple window in which every line they type is repeated on all other client windows.  The server maintains the state of the current line, and when it is changed by one of the clients all other clients are notified and update their screen.  This program is simply for research and so I can learn the Java language.  I need to use the Observable() interface.  This is what I have wrtiiten so far, I am new to programming and dont know how to create observers:

import java.io. *;
import java.net. *;
import java.util.*;


public class MessageServer extends Observable{
       
    private String Latest = "";  //This is the latest line entered from one of the clients
   
    /** Creates a new instance of MessageServer */
    public MessageServer() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        ServerSocket myServerSocket = null;
        try{
            myServerSocket = new ServerSocket(1234);
        } catch (IOException e) {
            System.err.println("Error listening on port 1234");
            System.exit(-1);
        }
       
        while(true)
        {
            //Accept the connection request
            new MessageClientThread(myServerSocket.accept()).start();
            //Create a thread to deal with the Client
        }
    }
   
}

As you can see the program accepts connections and starts threads of MessageClientThread.  These were going to be observers of this program which should extend the Observable interface.  Every time the String Latest at the top of the program changes they should update.  However, I dont know how to create Observers.  i have tried changing the line:
            new MessageClientThread(myServerSocket.accept()).start();
to:
            addObserver(new MessageClientThread(myServerSocket.accept()).start());
but I get the error:
      non-static method addObserver(java.util.Observer) cannot be referenced from a static context

I suppose me not understanding this comes from my lack of knowledge of OO programming.  How if I have a main routine, (where the program starts) can I create objects just using the new keyword like this:

       new MessageClientThread(myServerSocket.accept()).start();

Surely if i do this then I have no handle (is this the right word) on the object, i.e. how do I reference it in the future?  I thought you had to do something liike this:

      MessageClientThread MyObject = new MessageClientThread(myServerSocket.accept()).start();

Thanks guys, much appreciated

Ashley
0
ashleycoker
Asked:
ashleycoker
  • 7
  • 4
1 Solution
 
ashleycokerAuthor Commented:
Oh and I almost forgot!,

I realise to implement Observers you create a class that implements the 'Observer' interface, but how do instances of this class know what object to Observe?  Where in what class do you say, 'I want this object to observe me'!

I am confused as usual!!

Thanks
Ashley :-)
0
 
objectsCommented:
myobservable.addObserver(myobserver);
0
 
objectsCommented:
You use the above to register Observer objects that are intested in beng notified when the Observable object changes.

Then when your Observable object makes a change you call notifyObservers() and this will call the update() method of all Observer objects that are listening.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
objectsCommented:
eg. if you want your client threads to be observers of MessageServer you would do something like:

MessageClientThread client = new MessageClientThread(myServerSocket.accept());
addObserver(client);
client.start();
0
 
ashleycokerAuthor Commented:
This is my code as you said:

public class MessageServer extends Observable {
       
    private String Latest = "";
   
    /** Creates a new instance of MessageServer */
    public MessageServer() {
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        ServerSocket myServerSocket = null;
        try{
            myServerSocket = new ServerSocket(1234);
        } catch (IOException e) {
            System.err.println("Error listening on port 1234");
            System.exit(-1);
        }
       
        while(true)
        {
            //Accept the connection request
            //new MessageClientThread(myServerSocket.accept()).start();
            //Create a thread to deal with the Client
            MessageClientThread client = new MessageClientThread(myServerSocket.accept());
            addObserver(client);
            client.start();
        }
    }
   
}

but i get the error:

MessageServer.java [44:1] non-static method addObserver(java.util.Observer) cannot be referenced from a static context
0
 
objectsCommented:
Move all the code in main into your ctor.
And in replace your main with:

public static void main(String[] args) throws IOException{
   new MessageServer();
}
0
 
ashleycokerAuthor Commented:
Thanks a bunch, at least it compiles now, but why was it giving that error?
0
 
objectsCommented:
main is a static method, which means it does not have an object instance associated with it. addObbserver() needs to be called on a object instance.
0
 
ashleycokerAuthor Commented:
Now I have done that, how do I get the clients to send a message to the server to update it, and the get the server to notifyObservers() .  How can the server notifyObservers when it is updated if it is in a loop waiting for client connections?

Cheers
Ashley :-)
0
 
objectsCommented:
> how do I get the clients to send a message to the server to update it

They need to open a socket connection, and send the details of the update.

> How can the server notifyObservers when it is updated if it is in a loop waiting for client connections?

notifyObservers() will be called from the MessageClientThread thread as a result of it telling the server to update the string.

0
 
objectsCommented:
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now