Summary: Observer, Sockets
The java.util.Observer/.Obervable interface provide a fundamental observation design pattern in Java. It is an abstraction that lets a number of client objects (the observers) be notified whenever a certain object or resource (the observable) changes in some way. The observers implement the Observer interface, which specifies that notification causes an Observer object’s update() method to be called.
import java.util.*; public class MessageBoard extends Observable { private String message; public String getMessage() { return message; } public void changeMessage( String message ) { this.message = message; setChanged();//the Observable calls the setChanged() and notifyObservers() methods to notify the observers notifyObservers( message ); } public static void main( String [] args ) { MessageBoard board = new MessageBoard();//MessageBoard creates a MessageBoard and registers two Student objects with it Student bob = new Student(); Student joe = new Student(); board.addObserver( bob );//Each Student object registers itself using this method board.addObserver( joe ); board.changeMessage("More Homework!");//Then it changes the message } } // end of class MessageBoard class Student implements Observer { public void update(Observable o, Object arg) {//Each Student object receives updates via its update() System.out.println( "Message board changed: " + arg ); }//When you run the code, you should see each Student object print the message as it is notified. }
-The classes of java.net fall into two general categories: the Sockets API for working with low-level Internet protocols and higher-level, web-oriented APIs that work with uniform resource locators (URLs).
-Sockets are the lowest-level tool in the general networking toolbox—you can use sockets for any kind of communications between client and server or peer applications on the Net, but you have to implement your own application-level protocols for handling and interpreting the data.
-The java.net packag supports a simplified, object-oriented socket interface that makes network communications considerably easier
- Sockets,DatagramSocket
-Socket class, which uses a connection-oriented and reliable protocol.
- DatagramSocket class, which uses a connectionless, unreliable protocol. A connectionless protocol is like the postal service. Applications can send short messages to each other, but no end-to-end connection is set up in advance and no attempt is made to keep the messages in order.
-In most cases, an application acting as a server creates a ServerSocket object and waits, blocked in a call to its accept() method, until a connection arrives. When it arrives,the accept() method creates a Socket object that the server uses to communicate with the client. A server may carry on conversations with multiple clients at once; in this case, there is still only a single ServerSocket , but the server has multiple Socket objects—one associated with each client as above shown
-Client Sample
try { Socket server = new Socket("foo.bar.com", 1234);//the client first creates a Socket for communicating with the server InputStream in = server.getInputStream(); OutputStream out = server.getOutputStream(); // write a byte out.write(42);//Once the connection is established, the client writes a single byte to the server // write a newline or carriage return delimited string PrintWriter pout = new PrintWriter( out, true ); pout.println("Hello!");//To send a string of text more easily, it then wraps a PrintWriter around the OutputStream // read a byte byte back = (byte)in.read(); // read a newline or carriage return delimited string BufferedReader bin = new BufferedReader( new InputStreamReader( in ) ); String response = bin.readLine();//reading a byte back from the server using InputStream ’s read() method and then creating a BufferedReader f//from which to get a full string of text // send a serialized Java object ObjectOutputStream oout = new ObjectOutputStream( out );//using an ObjectOutputStream to send object oout.writeObject( new java.util.Date() ); oout.flush(); server.close(); } catch (IOException e ) { ... }-Server Sample
// Meanwhile, on foo.bar.com... try { ServerSocket listener = new ServerSocket( 1234 );//creates a ServerSocket attached to port 1234 while ( !finished ) { Socket client = listener.accept(); // wait for connection InputStream in = client.getInputStream();//we enter a loop, waiting for the accept() method of the ServerSocket to return an active Socket con//nection from a client OutputStream out = client.getOutputStream(); // read a byte byte someByte = (byte)in.read(); // read a newline or carriage-return-delimited string BufferedReader bin = new BufferedReader( new InputStreamReader( in ) ); String someString = bin.readLine(); // write a byte out.write(43); // say goodbye PrintWriter pout = new PrintWriter( out, true ); pout.println("Goodbye!"); // read a serialized Java object ObjectInputStream oin = new ObjectInputStream( in ); Date date = (Date)oin.readObject(); client.close(); } listener.close(); } catch (IOException e ) { ... } catch (ClassNotFoundException e2 ) { ... }