Upload
marcus-owen
View
222
Download
3
Embed Size (px)
Citation preview
1
Java Network Programming Java Network Programming
James ChenJames [email protected]@mail.hit.edu.tw
2
Why use Java ? ReasonReason
Built-in network capability Easy to code with powerful packages Security guarantee We are familiar with it …
3
What can we do with Network program
資料的取得與顯示資料的取得與顯示 WEB/HTML, ftp, email, Database…
定期擷取資料定期擷取資料 Stock Info, Headline, news
傳送資料傳送資料 檔案儲存 大量平行運算
javaparty project ! http://www.ipd.uka.de/JavaParty/features.html/ http://www.distributed.net
互動式互動式點對點點對點的服務的服務 Game and Chatroom E-learning Network Server 網頁搜尋 : Spider, Agent, …
IBM aglet 電子商務電子商務
Shopping cart
4
In the future 無所不在的運算環境無所不在的運算環境
Jini ( framework for interchanging Info ) Interactive TV ( set-top box )Interactive TV ( set-top box ) Peer-to-Peer networkingPeer-to-Peer networking
Kazza eDonkey (eMule) ezPeer … …
5
Recall basic network concept
James ChenJames Chen
Lecture 1Lecture 1
6
What’s the Internet ? Millions of connected computing devices: hosts, Millions of connected computing devices: hosts,
end-systemsend-systems PCs workstations, servers PDAs, phones, toasters running network apps
Communication links Communication links fiber, copper, radio, satellite transmission rate ( = bandwidth )
RoutersRouters: forward packets (chunks of data) : forward packets (chunks of data) Various Various ProtocolsProtocols for different applications. for different applications.
7
What's the Internet: a service view
Communication infrastructure enables Communication infrastructure enables distributed applicationsdistributed applications: : Web, email, games, e-commerce, database., voting, file
(MP3) sharing Communication services provided to Communication services provided to
applications: applications: connectionless ( 無連接導向 ) connection-oriented ( 連接導向 )
reliable data transfer (error, order) flow control congestion control
8
Internet StandardsStandards Internet standards Internet standards
RFCRFC: Request for comments IETFIETF: Internet Engineering Task Force
9
What’s a ProtocolProtocol?
10
Data rates of popular digital circuit standards
11
Evolution of Networking
12
Three Laws of Computing Moore'sMoore's Law Law
Computing power doubles every 18 months Gilder'sGilder's Law Law
Network bandwidth capacity doubles every 12 months
Metcalfe'sMetcalfe's Law (Net Effect) Law (Net Effect) Value of network increases exponentially as
number of participants increases
13
What is a distributed system?
A collection of processes/processors that A collection of processes/processors that do not share memory or a clock do not share memory or a clock
14
Why Distributed Systems? Resource sharing Resource sharing Higher performance Higher performance Flexible Flexible Reliable Reliable Scalable Scalable Manageable Manageable
15
Characteristics of Distributed Systems Complex programming Complex programming Heterogeneous Heterogeneous Inherent problems Inherent problems
Network latency Concurrency issues Partial Failure
16
Waves of Computing
17
Many Kinds of Networks and Technologies
18
Distributed Objects
19
ISO/OSI Reference Model
20
TCP/IP Stacks
21
Encapsulation Between Protocol Layers
22
TCP/IP Communication
23
TCP segment structure
24
UDP segment structure
25
Example of Using TCP And IP Service Primitives
Process
TCP
IP
NAP-1
ServiceResponse Primitives
ServiceRequest Primitives
Send Deliver
Primitives
InternetPackets
Process
TCP
IP
NAP-2
ServiceResponse Primitives
ServiceRequest Primitives
Send Deliver
Primitives
Packets
Host A Host B
26
IP, TCP, UDP TCP v.s. UDPTCP v.s. UDP
優缺點比較 OthersOthers
ICMP IGMP ARP, RARP RSVP, …
27
IP Address and Domain Name DNS ( Host name v.s. IP Address )DNS ( Host name v.s. IP Address )
Domain Name System Java : class java.net.InetAddress
Port#Port# 1..65535 Privileged Port for well-known service: 1..1023 /etc/services
28
Which Java Package can we use? java.net packagejava.net package
provides the basic classes for you to write network program.
It contains It contains InetAddress Socket ServerSocket … …
29
The InetAddress Class
The The java.net.InetAddressjava.net.InetAddress class class represents an IP address. represents an IP address. It converts numeric addresses to host names
and host names to numeric addresses. Ex: www.hit.edu.tw 163.17.65.28 Relationship with DNS service ! It is used by other network classes like Socket and ServerSocket to identify hosts
30
Well-known Ports - 1
31
Well-known ports - 2
32
Practicing Time Open a “Open a “Dos promptDos prompt” window” window Type the following commandType the following command
C:\...> telnet entry.hit.edu.tw 13
C:\... telnet entry.hit.edu.tw 80
GET /index.html
33
定址: Internet Addresses IP v4IP v4
Each host on a TCP/IP internet is assigned a unique 32-bit internet address that is used in all communication with that host.
Four primary classes of IP addresses.Four primary classes of IP addresses.
0 Network Local Address
10 Network Local Address
110 Network Local Address
111
0 1 8 16 24 31
Class A
Class B
Class C
Class D
34
Special issues of IP Address Classless Inter-Domain RoutingClassless Inter-Domain Routing
163.17.64.0 / 19 193.168.100.120 / 29
Non-routable address (Private IP Address)Non-routable address (Private IP Address) 10.*.*.* 172.16.*.* ~ 172.31.*.* 192.168.*.*
Local loop-back addressLocal loop-back address 127.0.0.1
35
Firewall v.s. Proxy Server Why we need Why we need FirewallFirewall ? ?
Rule-based Cheap solution ? Focus on TCP/IP layer
Why we need Why we need Proxy ServerProxy Server ? ? How about Cache ? Focus on Application layer ( 有限 , 已知 )
36
Proxy Server – Connection point of view
37
Client-Server Architecture
38
Client-Server – cont. Examples of ApplicationExamples of Application
FTP,WWW Is it suitable to implement every Is it suitable to implement every
application with Client/Server model ?application with Client/Server model ? Peer-to-Peer NetworkPeer-to-Peer Network
both client and server roles
39
Internet Standards IETF RFCSIETF RFCS
Internet Engineering Task Force Requests For Comments
Document how much of the Internet works Ex: TCP/IP, MIME, and SMTP.
www.faqs.org/rfc/ , http://www.ietf.org/rfc.html
W3C standardsW3C standards World Wide Web Consortium Ex: HTTP, HTML, and XML.
40
IETF vs W3C IETF is based on “rough consensus and IETF is based on “rough consensus and
running code”running code” W3C tries to run W3C tries to run ahead ofahead of
implementationimplementation IETF is an informal organization open to IETF is an informal organization open to
participation by anyoneparticipation by anyone W3C is a vendor consortium open only to W3C is a vendor consortium open only to
companiescompanies
41
Standardization Track of RFC At every step of the standardization track, the At every step of the standardization track, the
proposal is in one of six states or maturity proposal is in one of six states or maturity levels:levels: Experimental 實驗性 Proposed standard 建議標準 Draft standard 草案標準 Standard 標準 ( less than 100 during 3000 RFCs ) Informational 資訊性 Historic 紀念性
42
Basic Web ConceptBasic Web Concept
43
Outlines URI/URLURI/URL HTMLHTML HTTPHTTP MIMEMIME CGI/FormCGI/Form Applet issueApplet issue
44
URI Uniform Resource IdentifierUniform Resource Identifier(( 制式資源識別碼制式資源識別碼 ))
a string of characters in a particular syntax that identifies a resource.
Format
scheme:scheme-specific-part 分成兩類分成兩類
URL : Uniform Resource Locators http://www.hinet.net/myweb/test.mov
URN : Uniform Resource Names urn:namespace:resource_name
45
URI – known schemes HTTPHTTP FTPFTP telnettelnet GopherGopher mailtomailto NewsNews UrnUrn FileFile datadata
46
URI - scheme-specific-part FormatFormat
//authority/path?query
47
URL Absolute URLAbsolute URL
Beginning with / or http://host/… Relative URLRelative URL
else
Which is better for porting web pages to Which is better for porting web pages to another site ?another site ?
48
The java.net.URL class A A URLURL object represents a URL. object represents a URL. The The URLURL class contains methods to class contains methods to
create new URLs parse the different parts of a URL get an input stream from a URL so you can read
data from a server get content from the server as a Java object
49
Markup Language SGMLSGML HTMLHTML XMLXML XHTMLXHTML WMLWML voiceXMLvoiceXML MathMLMathML SMILSMIL ……
Homework #1.1
50
HTTP Connection HTTP 1.0 vs HTTP 1.1HTTP 1.0 vs HTTP 1.1 Step 1 & 2 for connectionStep 1 & 2 for connection
1. Making the connection. 2. Making a request.
GET /index.html HTTP 1.0Accept: text/htmlAccept: text/plainUser-Agent: Lynx/2.4 libwww/2.1.4\r\n
Homework #1.2
51
HTTP Connection Step 3 & 4 for connectionStep 3 & 4 for connection
3. The response.HTTP 1.0 200 OKServer: NCSA/1.4.2MIME-version: 1.0Content-type: text/htmlContent-length: 107\r\n<html><Head>…
4. Closing the connection
52
Status code of HTTP - 1
53
Status code of HTTP - 2
54
Status code of HTTP - 3
55
MIME Multipurpose Internet Mail ExtensionsMultipurpose Internet Mail Extensions
Originally, it’s an open standard for sending multipart, multimedia data through Internet email.
It has become a widely used technique to describe a file's contents so that client software can tell the difference between different kinds of data.
It Supports almost a hundred predefined types of content.
Web server and client support at least text/html, text/plain and image/gif, image/jpeg
56
Forms : input data There are times when the server needs to There are times when the server needs to
get data from the client rather than the get data from the client rather than the other way around. The common way to other way around. The common way to do this is with a form like this one:do this is with a form like this one:
57
CGI stands forstands for C Common ommon GGateway ateway IInterfacenterface CGI is used to generate web pages CGI is used to generate web pages
dynamicallydynamically the browser invokes a program on the server
that creates a new page on the fly. Can be written in almost any languages, Can be written in almost any languages,
including Java, though currently most including Java, though currently most CGI programming is done in Perl, ASP, CGI programming is done in Perl, ASP, C, PHP, ….C, PHP, ….
58
Transfer data to server Get Get
Query String passed as Environment Variable Less than 200 characters
GET /cgi-bin/xxxx/chkID?uid=xxx+yy&pw=zzz
PostPost Header + \r\n + query data ! Useful for upload file with MIME !
59
URL Encoding Alphanumeric ASCII characters (a-z, A-Z, and Alphanumeric ASCII characters (a-z, A-Z, and
0-9) and the $-_.!*'(), punctuation symbols are 0-9) and the $-_.!*'(), punctuation symbols are left left unchangedunchanged. .
The The spacespace character is converted into a plus character is converted into a plus sign (sign (++). ).
Other charactersOther characters (e.g. &, =, ^, #, %, ^, {, and so (e.g. &, =, ^, #, %, ^, {, and so on) are translated into a on) are translated into a percent signpercent sign followed followed by the by the two hexadecimal digitstwo hexadecimal digits corresponding to corresponding to their numeric value. their numeric value.
60
For example The comma is ASCII character The comma is ASCII character 4444
(decimal) or 2C (hex). Therefore if the (decimal) or 2C (hex). Therefore if the comma appears as part of a URL it is comma appears as part of a URL it is encoded as encoded as %2C%2C. .
The query string The query string Author=Sadie, Julie&Title=Women Composers
is encoded as:is encoded as:Author=Sadie%2C+Julie&Title=Women+Composers
61
The URLEncoder class The The java.net.java.net.URLEncoderURLEncoder class class
contains a single static method which contains a single static method which encodes strings in encodes strings in x-www-form-url-x-www-form-url-encodedencoded format formatURLEncoder.encode(String s)
Of course, Java has another one, Of course, Java has another one, java.net.java.net.URLDecoderURLDecoder class, for class, for decoding encoded data !decoding encoded data !
62
For example - wrongString qs = String qs = "Author"Author==Sadie, JulieSadie, Julie&&TitleTitle==Women Composers";Women Composers";
String eqs = URLEncoder.encode(qs);String eqs = URLEncoder.encode(qs);
System.out.println(eqs);System.out.println(eqs);
The result is as following:The result is as following: Author%3dSadie%2c+Julie%26Title
%3dWomen+Composers
63
For example - correctString eqs = String eqs = "Author=" + URLEncoder.encode("Sadie, Julie");"Author=" + URLEncoder.encode("Sadie, Julie");
eqs += "eqs += "&&";";
eqs += "Title=";eqs += "Title=";
eqs += URLEncoder.encode("Women Composers");eqs += URLEncoder.encode("Women Composers");
This prints the properly encoded query This prints the properly encoded query string:string:
Author=Sadie%2c+Julie&Title=Women+Composers
64
Security issues in Applet - Network Security Restrictions
Applets may:Applets may: send data to the code base receive data from the code base
Applets may not:Applets may not: send data to hosts other than the code base receive data from hosts other than the code base