?
Solved

Implementing the Observable Interface

Posted on 2003-11-06
11
Medium Priority
?
308 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
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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…
Suggested Courses
Course of the Month14 days, 23 hours left to enroll

771 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