[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Implementing the Observable Interface

Posted on 2003-11-06
11
Medium Priority
?
311 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
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!

 
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
 
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 500 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 to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.
Suggested Courses

649 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