81Java与网络 Java提供的网络功能有三大类:URL, Socket, Datagram URL是三大功能中最高级的一种通过URL Java程序可以直接送出或读入网络上的数据 Socket是传统网络程序最常用的方式可以想象 为两个不同的程序通过网络的通信信道 Datagram是更低级的网络传输方式,它把数据 的目的纪录在数据包中,然后直接放在网络上
6 8.1 Java与网络 Java提供的网络功能有三大类: URL, Socket, Datagram. URL是三大功能中最高级的一种,通过URL Java程序可以直接送出或读入网络上的数据. Socket是传统网络程序最常用的方式,可以想象 为两个不同的程序通过网络的通信信道. Datagram是更低级的网络传输方式,它把数据 的目的纪录在数据包中,然后直接放在网络上
82使用URL 823通过URL读取Www服务器上的数据 将URL位置的数据转成一个数据流 URL reNew Chttp://www.pku.edu.cn/index.html DataInputstream data=new DataInputstream(url.open Stream) 从数据流中读出数据 String line=data. readlineo while (line! =null) line=data. readLineo DataInputstream URL Java程序
7 URL Java 程序 DataInputStream 8.2 使用URL 8.2.3 通过URL读取WWW服务器上的数据 将URL位置的数据转成一个数据流 URL url=new (http://www.pku.edu.cn/index.html” DataInputStream data=new DataInputStream(url.openStream()); 从数据流中读出数据 String line=data.readLine() while(line!=null) line=data.readLine()
8 http://www.pku.edu.cn/ <htmI> <heade<title><. ></title></head> <body connect TextField a Frame主类 TextArea c str=a getText action line strb. readlineo URL urlnew URL(str) Button CappendText(line_str) URL url b-urL.openStreamOr DataInputStream b
8 8.2 使用URL 例:从给定的位置中读数据(ReadURLData.prj) http://www.pku.edu.cn/ connect <html> <head><title><...></title></head> <body> action URL url Button Frame主类 str=a.getText() b=url.openStream() TextArea c line_str=b.readLine() c.appendText(line_str); TextField a URL url=new URL(str) DataInputStream b
public boolean action ( Event evt, Object arg) i tryi String line String str=textfield gettext; urlnew URL(Str); data=new DataInputstream(url. open Stream); while((line=data. readlineol =nut textarea appendText(ine); data close: )catch(MalformedURLException me) System, out. printIn( Error UrL); catch(IOException ie) System. out. printIn( "Error IO") return true;
9 8.2 使用URL public boolean action(Event evt, Object arg) { try{ String line; String str=textfield.getText(); url=new URL(str); data=new DataInputStream(url.openStream()); while((line=data.readLine())!=null){ textarea.appendText(line); } data.close(); }catch(MalformedURLException me){ System.out.println("Error URL"); }catch(IOException ie){ System.out.println("Error IO"); } return true; }
10 83访问cgi 起始页上的计数器及cgi程序( (script) 欢迎来访你是第囗27个来访者 你是第< img sro=“cgi-bin/ perl/counter. cgi”>个 来访者 客户端 cg程序名 服务器端 num+ HTML CG程序 Img
10 欢迎来访,你是第 1 2 7 个来访者! 你是第<img SRC=“/cgi-bin/perl/counter.cgi”>个 来访者 客户端 HTML 服务器端 CGI程序 num+ + img cgi程序名 8.3 访问cgi 起始页上的计数器及cgi程序(script)