Java Notes-13(Oberver, Sockets)

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.

[java]  view plain copy
  1. import java.util.*;  
  2. public class MessageBoard extends Observable {  
  3. private String message;  
  4. public String getMessage() {  
  5. return message;  
  6. }  
  7. public void changeMessage( String message ) {  
  8. this.message = message;  
  9. setChanged();//the  Observable calls the  setChanged() and  notifyObservers() methods to notify the observers  
  10. notifyObservers( message );  
  11. }  
  12. public static void main( String [] args ) {  
  13. MessageBoard board = new MessageBoard();//MessageBoard creates a  MessageBoard and registers two  Student objects with it  
  14. Student bob = new Student();  
  15. Student joe = new Student();  
  16. board.addObserver( bob );//Each  Student object registers itself using this method  
  17. board.addObserver( joe );  
  18. board.changeMessage("More Homework!");//Then it changes the message  
  19. }  
  20. // end of class MessageBoard  
  21. class Student implements Observer {  
  22. public void update(Observable o, Object arg) {//Each  Student object receives updates via its update()  
  23. System.out.println( "Message board changed: " + arg );  
  24. }//When you run the code, you should see each  Student object print the message as it is notified.  
  25. }  

-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

[java]  view plain copy
  1. try {  
  2. Socket server = new Socket("foo.bar.com"1234);//the client first creates a  Socket for communicating with the server  
  3. InputStream in = server.getInputStream();  
  4. OutputStream out = server.getOutputStream();  
  5. // write a byte  
  6. out.write(42);//Once the connection is established, the client writes a single byte to the server  
  7. // write a newline or carriage return delimited string  
  8. PrintWriter pout = new PrintWriter( out, true );  
  9. pout.println("Hello!");//To send a string of text more easily, it then wraps a  PrintWriter around the  OutputStream   
  10. // read a byte  
  11. byte back = (byte)in.read();  
  12. // read a newline or carriage return delimited string  
  13. BufferedReader bin =  
  14. new BufferedReader( new InputStreamReader( in ) );  
  15. 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  
  16. // send a serialized Java object  
  17. ObjectOutputStream oout = new  
  18. ObjectOutputStream( out );//using an  ObjectOutputStream to send object  
  19. oout.writeObject( new java.util.Date() );  
  20. oout.flush();  
  21. server.close();  
  22. }  
  23. catch (IOException e ) { ... }  
-Server Sample

[java]  view plain copy
  1. // Meanwhile, on foo.bar.com...  
  2. try {  
  3. ServerSocket listener = new ServerSocket( 1234 );//creates a  ServerSocket attached to port 1234  
  4. while ( !finished ) {  
  5. Socket client = listener.accept(); // wait for connection  
  6. 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  
  7. OutputStream out = client.getOutputStream();  
  8. // read a byte  
  9. byte someByte = (byte)in.read();  
  10. // read a newline or carriage-return-delimited string  
  11. BufferedReader bin =  
  12. new BufferedReader( new InputStreamReader( in ) );  
  13. String someString = bin.readLine();  
  14. // write a byte  
  15. out.write(43);  
  16. // say goodbye  
  17. PrintWriter pout = new PrintWriter( out, true );  
  18. pout.println("Goodbye!");  
  19. // read a serialized Java object  
  20. ObjectInputStream oin = new ObjectInputStream( in );  
  21. Date date = (Date)oin.readObject();  
  22. client.close();  
  23. }  
  24. listener.close();  
  25. }  
  26. catch (IOException e ) { ... }  
  27. catch (ClassNotFoundException e2 ) { ... }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值