Solved

Implementing the Observable Interface

Posted on 2003-11-06
11
301 Views
Last Modified: 2013-11-23
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
Comment
Question by:ashleycoker
  • 7
  • 4
11 Comments
 

Author Comment

by:ashleycoker
ID: 9697836
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
 
LVL 92

Expert Comment

by:objects
ID: 9697845
myobservable.addObserver(myobserver);
0
 
LVL 92

Expert Comment

by:objects
ID: 9697865
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
 
LVL 92

Expert Comment

by:objects
ID: 9697887
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
 

Author Comment

by:ashleycoker
ID: 9697931
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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 92

Expert Comment

by:objects
ID: 9697944
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
 

Author Comment

by:ashleycoker
ID: 9697981
Thanks a bunch, at least it compiles now, but why was it giving that error?
0
 
LVL 92

Expert Comment

by:objects
ID: 9698016
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
 

Author Comment

by:ashleycoker
ID: 9698019
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
 
LVL 92

Accepted Solution

by:
objects earned 125 total points
ID: 9698047
> 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
 
LVL 92

Expert Comment

by:objects
ID: 9718429
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
stringclean challenge 26 58
nestparen challenge 4 57
XML Paring  Error - Premature end of file. 7 57
unix in java example 9 43
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now