64
1 Java Network Java Network Programming Programming James Chen James Chen [email protected] [email protected]

1 Java Network Programming James Chen [email protected]

Embed Size (px)

Citation preview

Page 1: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

1

Java Network Programming Java Network Programming

James ChenJames [email protected]@mail.hit.edu.tw

Page 2: 1 Java Network Programming James Chen jameschen@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 …

Page 3: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 4: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 … …

Page 5: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

5

Recall basic network concept

James ChenJames Chen

Lecture 1Lecture 1

Page 6: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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.

Page 7: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 8: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

8

Internet StandardsStandards Internet standards Internet standards

RFCRFC: Request for comments IETFIETF: Internet Engineering Task Force

Page 9: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

9

What’s a ProtocolProtocol?

Page 10: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

10

Data rates of popular digital circuit standards

Page 11: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

11

Evolution of Networking

Page 12: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 13: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 14: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

14

Why Distributed Systems? Resource sharing Resource sharing Higher performance Higher performance Flexible Flexible Reliable Reliable Scalable Scalable Manageable Manageable

Page 15: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

15

Characteristics of Distributed Systems Complex programming Complex programming Heterogeneous Heterogeneous Inherent problems Inherent problems

Network latency Concurrency issues Partial Failure

Page 16: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

16

Waves of Computing

Page 17: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

17

Many Kinds of Networks and Technologies

Page 18: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

18

Distributed Objects

Page 19: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

19

ISO/OSI Reference Model

Page 20: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

20

TCP/IP Stacks

Page 21: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

21

Encapsulation Between Protocol Layers

Page 22: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

22

TCP/IP Communication

Page 23: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

23

TCP segment structure

Page 24: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

24

UDP segment structure

Page 25: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 26: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

26

IP, TCP, UDP TCP v.s. UDPTCP v.s. UDP

優缺點比較 OthersOthers

ICMP IGMP ARP, RARP RSVP, …

Page 27: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 28: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 … …

Page 29: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 30: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

30

Well-known Ports - 1

Page 31: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

31

Well-known ports - 2

Page 32: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 33: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 34: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 35: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 ( 有限 , 已知 )

Page 36: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

36

Proxy Server – Connection point of view

Page 37: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

37

Client-Server Architecture

Page 38: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 39: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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.

Page 40: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 41: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 紀念性

Page 42: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

42

Basic Web ConceptBasic Web Concept

Page 43: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

43

Outlines URI/URLURI/URL HTMLHTML HTTPHTTP MIMEMIME CGI/FormCGI/Form Applet issueApplet issue

Page 44: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 45: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

45

URI – known schemes HTTPHTTP FTPFTP telnettelnet GopherGopher mailtomailto NewsNews UrnUrn FileFile datadata

Page 46: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

46

URI - scheme-specific-part FormatFormat

//authority/path?query

Page 47: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 ?

Page 48: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 49: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

49

Markup Language SGMLSGML HTMLHTML XMLXML XHTMLXHTML WMLWML voiceXMLvoiceXML MathMLMathML SMILSMIL ……

Homework #1.1

Page 50: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 51: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 52: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

52

Status code of HTTP - 1

Page 53: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

53

Status code of HTTP - 2

Page 54: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

54

Status code of HTTP - 3

Page 55: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 56: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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:

Page 57: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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, ….

Page 58: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 !

Page 59: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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.

Page 60: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 61: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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 !

Page 62: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 63: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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

Page 64: 1 Java Network Programming James Chen jameschen@mail.hit.edu.tw

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