You are on page 1of 75

Ni dung mn hc

CHNG 1: CHNG 2: CHNG 3: CHNG 4: GII THIU V TCP/IP THIT K GII THUT CHO CHNG TRNH CLIENT/SERVER LP TRNH MNG TRN CC MI TRUNG PH DNG LP TRNH MNG VI JAVA

Lp trnh mng Chng 1

Ni dung mn hc(tt)
CHNG 5: CHNG 6: CHNG 7: CHNG 8: LP TRNH WEB CGI LP TRNH WEB VI CC CNG NGH PH BIN

NG DNG XML TRONG LP TRNH MNG


BO MT D LIU TRUYN

Lp trnh mng Chng 1

Ti liu tham kho


[1] Douglas E. Comer, Internetworking with TCP/IP, Prentice-Hall,1993. [2] W. Richard Stevens, Unix Network Programming, Prentice-Hall,1990. [3] Arthur Dumas, Programming Winsock, Sams Publishing,1995. [4] Merlin, Conrad Hughes ..., Java Network Programming, Manning Publications Co., 1997. [5] D. Travis Dewire, Second-Generation Client/Server Computing, Mc Graw-Hill, 1997. [6] John Shapley Gray, Interprocess Comunication in UNIX, Prentice-Hall,1997. [7] Deitel & Deitel. Java How to program, 3th edition, Prentice-Hall,1999. [8] Richard Anderson, ..., Professional Active Server Pages 3.0, Wrox Press, 1999. [9] Marty Hall, Core Servlet and Java Server Pages, Prentice-Hall PTR, 2000 [10] MSDN. [11] Tp ti liu RFC.

Lp trnh mng Chng 1

Lp trnh mng Chng 1

CHNG 1 GII THIU V TCP/IP


1.1 Tng qut v TCP/IP. 1.2 Cc giao thc v dch v trn TCP/IP. 1.3 Khi nim v Socket. 1.4 Mt s ng dng mng.

Lp trnh mng Chng 1

1.1 Tng qut v TCP/IP.


OSI
Application Presentation Session Transport

TCP/IP
Applications layer Telnet FTP SMTP DNS SNMP

Transport layer (host level)

TCP

UDP

Network

Internet layer (gateway level)

ICMP ARP IP

Data link Network interface layer Physical

Ethernet

Token Ring

FDDI

WANs

Lp trnh mng Chng 1

1.1 Tng qut v TCP/IP (tt)


Mt s c tnh :
c lp v hnh thi ca mng. c lp v phn cng ca mng. Cc chun giao thc m. M hnh a ch ton cu. Nn tng client/server mnh m. Cc chun v giao thc ng dng mnh m.

Lp trnh mng Chng 1

1.1 Tng qut v TCP/IP (tt)

Lp trnh mng Chng 1

1.1 Tng qut v TCP/IP (tt)


a ch Internet:

nh v duy nht mt my Chiu di 32 bit Cu trc IP (netid, hostid), cc my trn mt mng c netid ging nhau. Do NIC cp Cch biu din:
10101100 00011100 172 28 172.28.16.5 00010000 16 00000101 5
9

Lp trnh mng Chng 1

1.1 Tng qut v TCP/IP (tt)


Phn lp a ch:
xc nh netid (Network Identifier) v hostid (Host Identifier)

Lp trnh mng Chng 1

10

1.1 Tng qut v TCP/IP (tt)


Mt s a ch IP c bit

Lp trnh mng Chng 1

11

1.1 Tng qut v TCP/IP (tt)


Lp Transport
Cung cp giao tip lun l gia cc processes trn cc hosts khc nhau C hai dng dch v:
TCP (Transmittion Control
Protocol)
application transport network data link physical network data link physical network data link physical network data link physical

g lo

a ic

le -e nd nd

network data link physical

s an tr

network data link physical application transport network data link physical

rt po

UDP (User Datagram


Protocol)
Lp trnh mng Chng 1

12

1.1 Tng qut v TCP/IP (tt)


Lp Transport (tt)
M rng cch nh a ch cho process. a ch port : xc nh ng dng mng trn mi my. a ch ca mt ng dng mng (IP,port)
Lp trnh mng Chng 1 13

1.2 Cc giao thc v dch v


H thng tn min DNS (Domain Name System)
Dng chui k t nh a ch, khng phn bit ch hoa, thng, mi thnh phn c th 63 k t v tn y khng di qu 255, di y gi l tn. Tn c t theo cy phn cp a ch ti nguyn biu din dng tn c hnh thnh t n cho n root
Lp trnh mng Chng 1 14

1.2 Cc giao thc v dch v (tt)


H thng tn min DNS (tt)

Lp trnh mng Chng 1

15

1.2 Cc giao thc v dch v(tt)


H thng tn min DNS (tt)
Network ch hiu a ch IP (binary) => nh x gia a ch IP v tn. H thng tn min c hin thc theo distributed database, qun l theo dng phn cp vi name servers Network ch hiu a ch IP (binary) => nh x gia a ch IP v tn. Mi ng dng mng phi chuyn tn sang a ch IP
Lp trnh mng Chng 1 16

1.2 Cc giao thc v dch v(tt)


DNS (tt)
ng dng giao tip vi local name server hi a ch nh x. Local name server s tr li hoc request tip
2 3 4 7 local name server
dns.eurecom.fr

root name server iterated query

intermediate name server dns.umass.edu

requesting host
surf.eurecom.fr
Lp trnh mng Chng 1

authoritative name server dns.cs.umass.edu

17 gaia.cs.umass.edu

1.2 Cc giao thc v dch v(tt)


Giao thc lp ng dng
ng dng mng : trao i thng tin gia cc processes trn mng. Cc ng dng phi nh ngha protocol giao tip vi nhau. Protocol qui nh th t cc thng ip trao i, hnh ng khi nhn mi loi thng ip. ng dng cng phi hin thc phn giao tip vi ngi dng.
Lp trnh mng Chng 1 18

1.2 Cc giao thc v dch v(tt)


Giao thc lp ng dng(tt)
User agent l giao tip gia ngi s dng v ng dng mng.
Web:browser E-mail: mail reader streaming audio/video: media player

Lp trnh mng Chng 1

19

1.2 Cc giao thc v dch v(tt)


M hnh mng client/server
Server : l phn t th ng
Ch yu cu t client, x l v tr kt qu cho client

Client : l phn t ch ng
Kt ni n server gi yu cu. Ch nhn kt qu tr v v x l kt qu.

Lp trnh mng Chng 1

20

1.2 Cc giao thc v dch v(tt)


State v Stateless
State : lu gi trng thi gia cc ln kt ni (request/response). Stateless : Mi ln request/response th cu ni hy b. Khng gi trng tri trc .

Lp trnh mng Chng 1

21

1.3 Khi nim v Socket.


Socket API
c gii thiu BSD4.1 UNIX, 1981 c ng dng khi to, s dng hay hy b Dng c ch client/server Cung cp hai dch v chuyn d liu thng qua socket API:
unreliable datagram reliable, byte stream-oriented
Lp trnh mng Chng 1 22

1.3 Khi nim v Socket(tt)


Socket :
L mi trng cc process ng dng giao tip vi nhau, process ng dng c th chy trn cng mt my hoc trn hai my khc nhau. c ng dng to ra v s dng tuy nhin c h thng (h iu hnh) kim sot.

Lp trnh mng Chng 1

23

1.3 Khi nim v Socket(tt)


Socket: ca nm gia process ng dng v end-endtransport protocol (UCP or TCP)

TCP service: dch v truyn tin cy chui bytes gia hai


process
controlled by application developer controlled by operating system

process socket TCP with buffers, variables

process socket TCP with buffers, variables

controlled by application developer controlled by operating system

internet

host or server
Lp trnh mng Chng 1

host or server
24

1.3 Khi nim v Socket(tt)


Lp trnh socket vi TCP
Client phi kt ni n server
server process phi chy trc (phn t th ng) server phi to mt socket lng nghe v chp nhn cc kt ni t client

Client kt ni n server bng cch:


Khi to TCP socket local Xc nh IP address, port number ca server process v kt ni n
Lp trnh mng Chng 1 25

1.3 Khi nim v Socket(tt)


Lp trnh socket vi TCP(tt)
Sau khi client khi to socket, n s thit lp kt ni n server Khi server nhn yu cu kt ni, n s chp nhn yu cu v khi to socket mi giao tip vi client.
Cho php server chp nhn nhiu client ti mt thi im.

Lp trnh mng Chng 1

26

1.3 Khi nim v Socket(tt) Server (running on hostid)


Client
create socket, port=x, for incoming request: welcomeSocket = ServerSocket() wait for incoming connection connection request connectionSocket = welcomeSocket.accept() read request from connectionSocket write reply to connectionSocket close connectionSocket Lp trnh mng Chng 1

TCP

setup

create socket, connect to hostid, port=x clientSocket = Socket() send request using clientSocket

read reply from clientSocket close clientSocket 27

Example: Java client (TCP)


import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; Create input stream Create client socket, connect to server Create output stream attached to socket BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
Lp trnh mng Chng 1 28

Example: Java client (TCP), cont.


Create input stream attached to socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); Send line to server Read line from server outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
Lp trnh mng Chng 1 29

Example: Java server (TCP)


import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
Lp trnh mng Chng 1 30

Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket

Example: Java server (TCP), cont


Create output stream, attached to socket Read in line from socket Write out line to socket } } End of while loop, loop back and wait for another client connection
Lp trnh mng Chng 1 31

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); }

1.3 Khi nim v Socket(tt)


Lp trnh socket vi UTP
Cung cp c ch truyn khng tin cy cc nhm cc byte (datagrams) gia client v server. Khng cn thit lp kt ni gia client vi server. Sender phi gi km a ch IP v port ch Server khi nhn d liu s phn tch a ch ca sender truyn li.

Lp trnh mng Chng 1

32

1.3 Khi nim v Socket(tt)


Lp trnh socket vi UTP(tt)
Server (running on hostid)
create socket, port=x, for incoming request: serverSocket = DatagramSocket()

Client
create socket, clientSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket

read request from serverSocket write reply to serverSocket specifying client host address, port umber Lp trnh mng Chng 1

read reply from clientSocket close clientSocket 33

Example: Java client (UDP)


import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes();
Lp trnh mng Chng 1 34

Create input stream Create client socket Translate hostname to IP address using DNS

Example: Java client (UDP), cont.


Create datagram with data-to-send, length, IP addr, port Send datagram to server Read datagram from server
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } }
Lp trnh mng Chng 1 35

Example: Java server (UDP)


import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket);
Lp trnh mng Chng 1 36

Create datagram socket at port 9876

Create space for received datagram Receive datagram

Example: Java server (UDP), cont


String sentence = new String(receivePacket.getData());

Get IP addr port #, of sender

InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase();

Create datagram to send to client Write out datagram to socket


} }

sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); }

End of while loop, loop back and wait for another datagram
Lp trnh mng Chng 1 37

1.4 Mt s ng dng mng.


World Wide Web (W W W)
Dng giao thc http: hypertext transfer protocol Webs application layer protocol M hnh client/server client: browser gi yu cu, nhn v hin th kt qu. server: Web server gi kt qu cho client i vi mi request. http1.0: RFC 1945 http1.1: RFC 2068
htt pr eq u es t pr esp ons e

PC running Explorer

htt

htt

eq pr

st ue

t ht

es pr

nse po

Server running NCSA Web server

Mac running Navigator


38

Lp trnh mng Chng 1

1.4 Mt s ng dng mng(tt)


W W W (tt) http: TCP transport service:
client khi to TCP connection (to socket) n server, port 80 (default) server chp nhn kt ni t client http messages (application-layer protocol messages) c trao i gia browser (http client) v Web server (http server) ng TCP connection
Lp trnh mng Chng 1 39

1.4 Mt s ng dng mng(tt)


W W W (tt) V d
User nh a ch URL ln browser
http://www.dit.hcmut.edu.vn/~phu/courses/net-programming/index.html 1a. http client to TCP connection (to socket) n http server www.dit.hcmut.edu.vn Port 80 2. http client gi http request message (cha ng dn) thng qua TCP connection time socket

1b. http server a ch www.dit.hcmut.edu.vn ang ch i kt ni port 80, chp nhn kt ni v notifying n client

Lp trnh mng Chng 1

40

1.4 Mt s ng dng mng(tt)


W W W (tt) V d
3. http server nhn yu cu, to response message (/~phu/courses/netprogramming/index.html) tr kt qu, gi message qua socket 4. http server ng cu ni TCP

time

5. http client nhn response message cha file html v hin th. Phn tch file html tm cc lin kt 6. Lp li cc bc 1-5 cho mi lin kt(object)

Lp trnh mng Chng 1

41

1.4 Mt s ng dng mng(tt)


W W W (tt)
C hai dng message trong http : request, response http request message:
ASCII (human-readable format)

Lp trnh mng Chng 1

42

1.4 Mt s ng dng mng(tt)


W W W (tt)
http request message:
request line (GET, POST, HEAD commands) GET /~phu/index.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg header Accept-language:vn lines (extra carriage return, line feed)

Carriage return, line feed indicates end of message

Lp trnh mng Chng 1

43

1.4 Mt s ng dng mng(tt)


W W W (tt)
http response message:
status line (protocol status code status phrase) header lines HTTP/1.0 200 OK Date: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 ... Content-Length: 6821 Content-Type: text/html data data data data data ...
Lp trnh mng Chng 1 44

data, e.g., requested html file

1.4 Mt s ng dng mng(tt)


client
Authentication goal: control access to server documents stateless: client must present authorization in each request authorization: typically name, password authorization: header line in request if no authorization presented, server refuses access, sends
WWW authenticate:

server
401: authorization req. WWW authenticate: usual http request msg + Authorization:line

usual http request msg

usual http response msg usual http request msg + Authorization:line usual http response msg

header line in response

time
45

Browser caches name & password so Lp trnh mng Chng 1 that user does not have to repeatedly enter it.

1.4 Mt s ng dng mng(tt)


Cookies
server sends cookie to client in response mst
Set-cookie: 1678453

client
usual http request msg usual http response +

server

client presents cookie in later requests


cookie: 1678453

Set-cookie: #
usual http request msg

server matches presentedcookie with server-stored info authentication remembering user preferences, previous choices

cookie: #
usual http response msg usual http request msg

cookiespectific action cookiespectific action


46

cookie: #
usual http response msg

Lp trnh mng Chng 1

1.4 Mt s ng dng mng(tt)


Conditional GET
Goal: dont send object if client has up-to-date stored (cached) version client: specify date of cached copy in http request
If-modified-since: <date>

client
http request msg
If-modified-since: <date>

server
object not modified

http response
HTTP/1.0 304 Not Modified

server: response contains no object if cached copy up-to-date:


HTTP/1.0 304 Not Modified

http request msg


If-modified-since: <date>

http response
HTTP/1.1 200 OK
Lp trnh mng Chng 1

object modified

<data>

47

1.4 Mt s ng dng mng(tt)


File Transfer Protocol (ftp)
FTP user interface FTP client local file system file transfer FTP server remote file system

user at host

Chuyn file t local n server hoc ly file t server v local. Hot ng theo c ch client/server FTP server chy port 21. Tham kho : RFC 959
Lp trnh mng Chng 1 48

1.4 Mt s ng dng mng(tt)


FTP (tt)
ftp client giao tip n ftp server qua TCP port 21 Hai cu ni TCP c thit lp: control: exchange commands, responses between client, server. out of band control data: file data to/from server ftp server hin thc c ch state: current directory, earlier authentication

Lp trnh mng Chng 1

49

1.4 Mt s ng dng mng(tt)


Sample commands:
sent as ASCII text over control channel USER username PASS password LIST return list of file in current directory RETR filename retrieves (gets) file STOR filename stores (puts) file onto remote host
Lp trnh mng Chng 1 50

1.4 Mt s ng dng mng(tt)


Sample return codes
status code and phrase (as in http) 331 Username OK, password required 125 data connection already open; transfer starting 425 Cant open data connection 452 Error writing file

Lp trnh mng Chng 1

51

1.4 Mt s ng dng mng(tt)


H thng E-mail
RFC 821, 822 SMTP: port 25 POP3: port 110 IMAP: port 143
user agent mail server user agent mail server user agent

SMTP SMTP
mail server outgoing message queue user mailbox

SMTP
user agent

user agent

user agent

Lp trnh mng Chng 1

52

1.4 Mt s ng dng mng(tt)


H thng E-mail V d v SMTP S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <alice@crepes.fr> S: 250 alice@crepes.fr... Sender ok C: RCPT TO: <bob@hamburger.edu> S: 250 bob@hamburger.edu ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection
Lp trnh mng Chng 1 53

V d v POP3
client commands: user: declare username pass: password server responses +OK -ERR

S: C: S: C: S: C: S: S: S: C: S: S: C: C: S: S: C: C: S:

+OK POP3 server ready user alice +OK pass hungry +OK user successfully logged list 1 498 2 912 . retr 1 <message 1 contents> . dele 1 retr 2 <message 1 contents> . dele 2 quit +OK POP3 server signing off

on

transaction phase, client:


list: list message numbers retr: retrieve message by number dele: delete quit

Lp trnh mng Chng 1

54

CHNG 2 THIT K GII THUT CHO CHNG TRNH CLIENT/SERVER


2.1 Giao tip socket (Socket Interface ) 2.2 Thit k gii thut cho chng trnh client 2.3 Thit k gii thut cho chng trnh server

Lp trnh mng Chng 2

55

2.1 Giao tip socket


Giao tip socket (Socket Interface) l cc API dng cho vic lp trnh cc ng dng mng. Socket Interface c nh ngha trong UNIX BSD, da trn vic m rng tp cc system calls (access files). => Phn ny ch gii thiu cc khi nim, tng v cc hm, kiu d liu dng cho lp trnh mng vi Socket Interface.
Lp trnh mng Chng 2 56

2.1 Giao tip socket (tt)


Mt s cu trc d liu
Cu trc a ch Internet : nh ngha dng d liu cu
trc trong ngn ng C. Cu trc ny ch c 1 field kiu u_long cha a ch IP 32 bit.
struct { }; in_addr u_long s_addr;
s_addr in_addr

Hnh - cu trc a ch Internet


Lp trnh mng Chng 2 57

2.1 Giao tip socket (tt)


Mt s cu trc d liu (tt)
Cu trc a ch socket :
a ch ny lu tr a ch IP, ch s port, v dng (family protocol) Tn cu trc l sockaddr_in c biu din hnh trong slide k. Trong :
sin_len: lu tr chiu di cu trc ca sockaddr_in sin_family: dng protocol ca socket sin_port: ch s port sin_addr: a ch in Internet ca socket sin_zero[8]: khng dng, t gi tr = 0
Lp trnh mng Chng 2 58

2.1 Giao tip socket (tt)


sin_len sin_family sin_port sin_addr sockaddr_in struct sockaddr_in { u_char u_short u_short struct char };
Lp trnh mng Chng 2 59

sin_zero

Hnh - Cu trc a ch socket


sin_len; sin_family; sin_port;

in_addr

sin_addr; sin_zero[8];

2.1 Giao tip socket (tt)


Mt s cu trc d liu (tt)
Cu trc socket :
socket c nh ngha trong h iu hnh bng mt cu trc, c xem nh im ni hai procceses giao tip vi nhau. Cu trc socket gm 5 field c m t nh hnh trong slide k:
Family : xc nh protocol group Type : xc loi socket, stream, datagram hay raw socket. Protocol : l field thng gn gi tr bng 0 Local Socket Address v Remote Socket Address : l a ch socket ca process cc b v t xa.
Lp trnh mng Chng 2 60

2.1 Giao tip socket (tt)


Family Type Protocol

sin_len

sin_family

sin_port

sin_addr

sin_zero

Local Socket Address

sin_len

sin_family

sin_port

sin_addr

sin_zero

Remote Socket Address Socket

Lp trnh mng Chng 2

61

2.1 Giao tip socket (tt)


Mt s cu trc d liu (tt)
Loi socket :
Giao tip socket nh ngha 3 loi socket c th dng trn mi trng TCP/IP (hnh slide k). Cc loi socket gm:
Stream Socket: dng cho connection-oriented protocol nh TCP. Datagram Socket: dng cho connectionless protocol nh UDP. Raw Socket: dng cho mt s protocol ca mt s ng dng c bit, dng cc dch v trc tip ca lp IP.

Lp trnh mng Chng 2

62

2.1 Giao tip socket (tt)


Application program
Stream socket interface Datagram socket interface Raw socket interface

TCP

UDP IP

Physical and datalink layers

Hnh - Cc loi socket


Lp trnh mng Chng 2 63

Mt s cu trc d liu (tt)


Thng tin remote host :
Thng tin c lu tr trong mt cu trc hostent c tr v khi ng dng mun nh x a ch tn min bng cch gi hm gethostbyname(): struct hostent * gethostbyname(const char * hostname); struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; }
Lp trnh mng Chng 2 64

2.1 Giao tip socket (tt)


Mt s cu trc d liu (tt)
Byte Ordering
Big-Endian Byte Order : byte c trng s ln lu trc. Little -Endian Byte Order : byte c trng s nh lu trc. Tu cu trc ca mi my, lu tr s theo mt trong hai cch trn => khi giao tip mng s khng ng nht.

Lp trnh mng Chng 2

65

2.1 Giao tip socket (tt)


Mt s cu trc d liu (tt)
Byte Ordering (tt)
Network Byte Order : th t lu tr dng cho giao tip mng. Giao tip socket nh ngha mt s hm thc hin cc thao tc chuyn i :
htons v htonl : chuyn t dng lu tr ca my sang Network ntohs v ntohl : chuyn t dng lu tr ca Network sang dng lu tr ca my.

Lp trnh mng Chng 2

66

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket
Hm socket() to mi mt socket
int socket (int family, int type, int protocol);

Hm ny to mt socket, kt qu tr v l mt s nguyn nhn dng (socket descriptor), nu c li gi tr tr v l -1. Cc thng s :


family: h socket type: kiu socket (stream hay datagram) protocol: giao thc, thng t bng 0
Lp trnh mng Chng 2 67

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm bind() ng k vi h thng
int bind (int sockfd, const struct sockaddr_in *localaddr, int localaddrlen);

ng k socket khi to vi a ch socket local. Tr v 0 nu thnh cng, -1 nu tht bi. Cc thng s :


sockfd: m t socket to bi hm socket() localaddr:con tr ch n a ch socket ca local localaddrlen: chiu di ca a ch socket
Lp trnh mng Chng 2 68

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm connect() kt ni n server
int connect(int sockfd, const struct sockaddr_in *serveraddr, int serveraddrlen);

Dng cho chng trnh client thit lp kt ni n server. Tr v 0 nu thnh cng, -1 nu tht bi. Cc thng s :
sockfd: m t socket to bi hm socket() serveraddr:con tr a ch socket ca server serveraddrlen: chiu di ca a ch socket server
Lp trnh mng Chng 2 69

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm listen() kt ni n server
int listen(int sockfd, int backlog);

Hm ny dng cho chng trnh server connection-oriented t socket trng thi ch, lng nghe kt ni t pha client. Tr v 0 nu thnh cng, -1 nu tht bi. Cc thng s:
sockfd: m t socket to bi hm socket() backlog: s request c th queued.

Lp trnh mng Chng 2

70

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm accept() : chp nhn kt ni t client n.
int accept(int sockfd, const struct sockaddr_in *clientaddr, int *clientaddrlen);

Chp nhn kt ni t client, to socket mi. Gi tr l mt socket descriptor ca socket mi. Cc thng s :
sockfd: m t socket to bi hm socket() clientaddr:con tr a ch socket ca client kt ni n. clientaddrlen: chiu di ca clientaddr
Lp trnh mng Chng 2 71

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm read() c d liu t socket
int read(int sockfd, const void *buf, int len);

c d liu t connection vo b nh. Tr v s bytes c c nu thnh cng, tr v 0 nu khng c d liu, tr v -1 nu tht bi. Cc thng s :
sockfd: m t socket to bi hm socket() buf: con tr n b m lu thng tin c c len: chiu di ca b m
Lp trnh mng Chng 2 72

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm write() ghi d liu
int write(int sockfd, const void *buf, int len);

Ghi d liu t b nh ln connection. Tr v s bytes ghi c nu thnh cng, tr v -1 nu tht bi. Cc thng s :
sockfd: m t socket to bi hm socket() buf: con tr n b m lu thng tin c c len: chiu di ca b m
Lp trnh mng Chng 2 73

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm sendto() gi d liu
int sendto(int sockfd, const void *buf, int len, int flags, const struct sockaddr_in *toaddr, int toaddrlen);

Gi d liu n mt a ch socket t xa. Tr v s bytes gi c nu thnh cng, tr v -1 nu tht bi. Cc thng s :


sockfd, buf, len: ging cc hm gii thiu flags: thng t bng 0 toaddr, toaddrlen: a ch socket n v chiu di.
Lp trnh mng Chng 2 74

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Hm recvfrom() nhn d liu
int recvfrom(int sockfd, const void *buf, int len, int flags, const struct sockaddr_in *fromaddr, int fromaddrlen);Nhn d liu t mt a ch socket t

xa. Tr v s bytes gi c nu thnh cng, tr v -1 nu tht bi. Cc thng s :

sockfd, buf, len: ging cc hm gii thiu fromaddr, fromaddrlen: a ch socket gi n v chiu di.
Lp trnh mng Chng 2 75

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Mt s hm dng cho vic chuyn i u_short htons(u_short host_short); u_short ntohs(u_short network_short); u_long htonl(u_long host_long); u_long ntohl(u_long network_long); char *inet_ntoa(struct in_addr inaddr) int inet_aton(const char *strptr, struct in_addr *addptr)
Lp trnh mng Chng 2 76

2.1 Giao tip socket (tt)


Cc hm dng cho lp trnh socket (tt)
Mt s hm dng cho vic thao tc d liu void *memset ( void *dest, int chr, int len); void *memcopy ( void *dest, void *src, int len) int memcmp ( const void *first, const void *second, int len)

Lp trnh mng Chng 2

77

2.2 Thit k gii thut cho chng trnh client


Gii thut cho chng trnh client dng TCP
Xc nh a ch server To socket. Kt ni n server. Gi/nhn d liu theo giao thc lp ng dng thit k. ng kt ni.

Lp trnh mng Chng 2

78

2.2 Thit k gii thut cho chng trnh client (tt)


Gii thut cho chng trnh client dng UCP
Xc nh a ch server To socket. ng k socket vi h thng. Gi/nhn d liu theo giao thc lp ng dng thit k n server theo a ch xc nh. ng kt ni.

Lp trnh mng Chng 2

79

2.3 Thit k gii thut cho chng trnh server


Chng trnh server c hai loi n gin : lp (iterative) v ng thi (concurrent). Hai dng giao thc chng trnh server c th s dng l connection-oriented hoc connectionless. Cc slide k tip trnh by cch thit k gii thut cho cc loi server kt hp cc c im trn
Lp trnh mng Chng 2 80

2.3 Thit k gii thut cho chng trnh server (tt)


Gii thut cho chng trnh server iterative, connection-oriented:
To socket, ng k a ch socket vi h thng. t socket trng thi lng nghe, ch v sn sng cho vic kt ni t client. Chp nhn kt ni t client, gi/nhn d liu theo giao thc lp ng dng thit k. ng kt ni sau khi hon thnh, tr li trng thi lng nghe v ch kt ni mi.
Lp trnh mng Chng 2 81

2.3 Thit k gii thut cho chng trnh server (tt)


Gii thut cho chng trnh server iterative, connectionless:
To socket v ng k vi h thng. Lp cng vic c d liu t client gi n, x l v gi tr kt qu cho client theo ng giao thc lp ng dng thit k.

Lp trnh mng Chng 2

82

2.3 Thit k gii thut cho chng trnh server (tt)


Cc yu cu cho concurrent Server:
Ti mt thi im c th x l nhiu yu cu t client. Chng trnh concurrent server c th chy trn my ch c 1 CPU. H thng phi h tr multi-tasking

Lp trnh mng Chng 2

83

2.3 Thit k gii thut cho chng trnh server (tt)


Gii thut cho chng trnh concurrent, connectionless server:
To socket, ng k vi h thng. Lp vic nhn d liu t client, i vi mt d liu nhn, to mi mt process x l. Tip tc nhn d liu mi t client. Cng vic ca process mi :
Nhn thng tin ca process cha chuyn n, ly thng tin socket X l v gi thng tin v cho client theo giao thc lp ng dng thit k. Kt thc.

Lp trnh mng Chng 2

84

2.3 Thit k gii thut cho chng trnh server (tt)


Gii thut cho chng trnh concurrent, connectionoriented server:
To socket, ng k vi h thng. t socket ch ch, lng nghe kt ni. Khi c request t client, chp nhn kt ni, to mt process con x l. Quay li trng thi ch, lng nghe kt ni mi. Cng vic ca process mi gm:
Nhn thng tin kt ni ca client. Giao tip vi client theo giao thc lp ng dng thit k. ng kt ni v kt thc process con.
Lp trnh mng Chng 2 85

2.3 Thit k gii thut cho chng trnh server (tt)


Multi-protocol Server (TCP,UDP)
Dng mt chng trnh , m mt master socket cho c TCP v UDP. Dng hm h thng (select ) chn la TCP socket hay UDP socket sn sng. Ty vo protocol (TCP, UDP ) x l gi nhn thng ip theo ng giao thc ca lp ng dng. Tham kho thm RFC 1060
Lp trnh mng Chng 2 86

2.3 Thit k gii thut cho chng trnh server (tt)


Multi-service Server
To mt im giao tip chung. Vi mi request, xem loi dch v cn x l. Vi mi loi dch v, x l ring bit C th kt hp Multi-service v Multi-protocol thit k cho chng trnh server.

Lp trnh mng Chng 2

87

CHNG 3 LP TRNH MNG TRN CC MI TRNG PH DNG


3.1 Lp trnh mng trong UNIX 3.2 Cc hm h tr lp trnh mng trong UNIX 3.3 Lp trnh mng trong Windows vi TCP/IP 3.4 Cc hm h tr lp trnh mng trong Windows
Lp trnh mng Chng 3 88

2.1 Lp trnh mng trong UNIX


Lp trnh mng trong mi trng UNIX dng socket c cc hm ging BSD Socket Interface gii thiu.

Lp trnh mng Chng 3

89

3.2 Cc hm h tr lp trnh mng trong UNIX


a ch socket trn Internet v a ch IP:
#include <netinet/in.h> struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; struct in_addr{ u_long s_addr; }
Lp trnh mng Chng 3 90

3.2 Cc hm (tt)
a ch socket tng qut:
#include <sys/socket.h> struct sockaddr { short sa_family; char sa_data[14]; };

H a ch socket c nh ngha trong <sys/socket.h>:


#define AF_UNIX 1/* local to host (pipes, portals) */ #define AF_INET 2 /* internetwork: UDP, TCP, etc. */
Lp trnh mng Chng 3 91

3.2 Cc hm (tt)
Cu trc a ch my t xa.
struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; #define h_addr h_addr_list[0]; }
Lp trnh mng Chng 3 92

3.2 Cc hm (tt)
To socket:
#include <sys/types.h> #include <sys/socket.h>
int socket(int family, int type, int protocol);

V d to socket:
int sockfd; //To stream socket sockfd = socket(AF_INET,SOCK_STREAM,0); //To datagram socket sockfd = socket(AF_INET,SOCK_DGRAM,0);
Lp trnh mng Chng 3 93

3.2 Cc hm (tt)
Lin kt socket vi a ch socket(ng k)
int bind(int sockfd, struct sockaddr *myaddr, int myaddrlen);

V d bind socket va to vi a ch socket:


struct sockaddr_in myaddr; bzero((char*)&myaddr,sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_port = htons(portno); myaddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) error("ERROR on binding");
Lp trnh mng Chng 3 94

3.2 Cc hm (tt)
Chuyn socket v trng thi ch kt ni.
int listen(int sockfd, int backlog);

Chp nhn yu cu kt ni t client.


int accept(int sockfd, struct sockaddr_in *peer, int *addrlen);
struct sockaddr_in cli_addr;int newsockfd,clilen; listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept");
Lp trnh mng Chng 3 95

3.2 Cc hm (tt)
Hm kt ni n server
int connect(int sockfd, struct sockaddr *servaddr, int *addrlen); V d:
struct sockaddr_in servaddr; bzero((char*)&servaddr,sizeof(myaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(portno); servaddr.sin_addr.s_addr = inet_addr(serverIP); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) error(Can not connect to server");
Lp trnh mng Chng 3 96

3.2 Cc hm (tt)
Cc hm truyn nhn d liu:
int read(int fd,char *buf, int nbytes); int write(int fd,char *buf,int nbytes); int send(int sockfd, char *buf,int nbytes,int flags); int recv(int sockfd, char *buf,int nbytes,int flags); int sendto(int sockfd, char *buf, int len, int flags, struct sockaddr_in *toaddr, int toaddrlen); int recvfrom(int sockfd, char *buf, int len, int flags, struct sockaddr_in *fromaddr, int fromaddrlen);

Lp trnh mng Chng 3

97

3.2 Cc hm (tt)
To process con x l tng kt ni:
int fork(void);
int pid; while(1){ newsockfd = accept(sockfd, (struct sockaddr*) &cli_addr, &clilen); if ((pid=fork())==0){ close(sockfd); process(newsockfd); close(newsockfd) exit(0); } close(newsockfd); }
Lp trnh mng Chng 3 98

3.3 Lp trnh mng trong Windows vi TCP/IP


Dng th vin WinSock API (Windows Sockets Application Programming Interface ) hin thc. Cn c th vin WINSOCK.DLL hoc WINSOCK32.DLL (32-bit Windows ). Cn include cc hm v cu trc t WINSOCK.H hoc WINSOCK2.H C th bin dch dng dng lnh : cl o dest-file src-file ws2_32.lib
Lp trnh mng Chng 3 99

3.3 Lp trnh mng trong Windows vi TCP/IP


WinSock hin thc Berkeley Sockets Interface trn mi trng Windows. WinSock c nhiu m rng thm so vi Berkeley Sockets.
H tr kin trc Windows Message-Driven hay event-driven. H tr kin trc nonpreemptive ca Windows

Lp trnh mng Chng 3

100

3.4 Cc hm h tr lp trnh mng trong Windows


Khi to WinSock:
int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData); V d :
WORD wVerRequested = MAKEWORD(0,1); WSADATA wsaData; if(WSAStartup(wVerRequested,&wsaData)!=0){ // process error }
Lp trnh mng Chng 3 101

3.4 Cc hm WinSock (tt)


Kt thc WinSock
int WSAClearup();

Hm ly thng tin li :
int WSAGetLastError(void);

Lp trnh mng Chng 3

102

3.4 Cc hm WinSock (tt)


Cm hm dng cho chuyn i:
Chuyn a ch IP dng chui sang nh phn: unsigned long inet_addr(const char FAR *cp); Chuyn a ch IP dng nh phn sang dng chui: char FAR *inet_ntoa(struct in_addr in); Ly a ch my cc b: int gethostname(char FAR*name,int len); Ly a ch my t xa: struct hostent FAR *gethostbyname(const char FAR *name);
Lp trnh mng Chng 3 103

3.4 Cc hm WinSock (tt)


V d v ly a ch PHOSTENT phe = gethostbyname(condlg.m_remotehost); char szTemp[128]; if (phe == NULL) { wsprintf(szTemp,Not exist '%s'", condlg.m_remotehost); MessageBox(szTemp); return; } memcpy((char FAR *)&(ser_addr.sin_addr), phe>h_addr,phe->h_length);
Lp trnh mng Chng 3 104

3.4 Cc hm WinSock (tt)


Hm to socket
SOCKET socket ( int af, int type, int protocol ); af :h socket (thng dng AF_INET : Internet) type : loi socket (SOCK_STREAM, SOCK_DGRAM) protocol : giao thc, thng t = 0 ly gi tr default tr v gi tr INVALID_SOCKET nu c li V d v hm to socket : ser_sock=socket(AF_INET,SOCK_STREAM,0); if(ser_sock==INVALID_SOCKET) { MessageBox(Can not create socket"); return TRUE; }
Lp trnh mng Chng 3 105

3.4 Cc hm WinSock (tt)


Hm ng k a ch socket vi h thng
int bind (SOCKET s, const struct sockaddr FAR *addr, int addrlen ); s : m t socket c khi to. addr : a ch socket. addrlen : chiu di addr Nu c li tr v gi tr SOCK_ERROR

Lp trnh mng Chng 3

106

3.4 Cc hm WinSock (tt)


V d v lnh bind :

//
char message[100]; SOCKADDR_IN addr; addr.sin_family=AF_INET; addr.sin_port=htons(2000); addr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(s,(LPSOCKADDR)&addr,sizeof(addr))== SOCKET_ERROR){ wsprintf(message, Can not bind socket : %d, WSAGetLastError()); MessageBox(message); return TRUE; }
Lp trnh mng Chng 3 107

3.4 Cc hm WinSock (tt)


Hm chuyn socket v trng thi ch
int listen (SOCKET s, int backlog ); backlog : chiu di hng i tr v gi tr SOCKET_ERROR nu c li V d v hm listen: if(listen(s,5)==SOCKET_ERROR) { wsprintf(message, Can not listen : %d, WSAGetLastError()); MessageBox(message); return TRUE; }
Lp trnh mng Chng 3 108

3.4 Cc hm WinSock (tt)


Hm chp nhn kt ni t client.
SOCKET accept (SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen ); s : l m t socket ca server.

: con tr a ch socket ca client kt ni n. addrlen : chiu di ca addr


addr

Lp trnh mng Chng 3

109

3.4 Cc hm WinSock (tt)


V d v hm accept :
SOCKADDR_IN client_addr;SOCKET cli_s; IN_ADDR clientIP; int len=sizeof(client_addr); cli_S=accept(s,(LPSOCKADDR)&client_addr,&len); if(sock==INVALID_SOCKET) { MessageBox(Can not eccept"); return TRUE; } else { memcopy(&clientIP,&client_addr.sin_addr.s_addr,4); wsprintf(message,Client IP= %s and port= %d, inet_ntoa(clientIP),ntohs(cli_s.sin_port));

}
Lp trnh mng Chng 3 110

3.4 Cc hm WinSock (tt)


Hm thit lp kt ni n server.
int connect (SOCKET s, const struct sockaddr FAR *name, int namelen ); s : socket ca chng trnh local name : a ch socket ca server. namelen : chiu di ca name Tr v gi tr SOCKET_ERROR nu c li

Lp trnh mng Chng 3

111

3.4 Cc hm WinSock (tt)


V d v hm connect SOCKADDR_IN ser_addr; ser_addr.sin_family=AF_INET; ser_addr.sin_port=htons(2000); ser_addr.sin_addr.s_addr= inet_addr(172.28.10.20); if(connect(s,(LPSOCKADDR)&ser_addr, sizeof(ser_addr))==SOCKET_ERROR){ MessageBox(Can not connect to server); }
Lp trnh mng Chng 3 112

3.4 Cc hm WinSock (tt)


Lnh gi d liu int send (SOCKET s, const char FAR * buf, int len, int flags );
buf : chui d liu cn gi len : chiu di ca buf flags : thng t gi tr 0 Tr v s byte d liu gi c, nu li tr v SOCKET_ERROR //... char buf[255]; lstrcpy(mesg,Hello World); if (send(s,buf,strlen(buf),0) ==SOCKET_ERROR) { MessageBox(Can not send data"); return; }
Lp trnh mng Chng 3 113

3.4 Cc hm WinSock (tt)


int recv ( SOCKET s, char FAR* buf, int len, int flags ); Cc thng s tng t hm send
//

#define BUFSIZE (100) char buf[BUFSIZE]; int nByteRecv; nByteRecv = recv(s,buf, BUFSIZE,0); if (nByteRecv == SOCKET_ERROR) { MessageBox(Error receive data"); return; } //
Lp trnh mng Chng 3 114

3.4 Cc hm WinSock (tt)


Cc hm dng cho UDP
int sendto (SOCKET s, const char FAR *buf, int len, int flags, const struct sockaddr FAR *to, int tolen); to : a ch socket ca process mun gi n int recvfrom ( SOCKET s, char FAR* buf, int len, int flags,const struct sockaddr FAR *from, int FAR *fromlen ); from : a ch socket ca process gi d liu n

Lp trnh mng Chng 3

115

3.4 Cc hm WinSock (tt)


V d v hm sendto: #define BUFSIZE (100) char buf[BUFSIZE]; int nByteSend;
SOCKADDR_IN to; to.sin_family = AF_INET; to.sin_port = 2000; to.sin_addr.s_addr = inet_addr(127.0.0.1);

lstrcpy(buf,Hello World);
nByteSend = sendto(s,buf,lstrlen(buf),0, (LPSOCKADDR)&to,sizeof(to)); if(nByteSend == SOCKET_ERROR ) //
Lp trnh mng Chng 3 116

3.4 Cc hm WinSock (tt)


V d v hm recvfrom

#define BUFSIZE (100) char buf[BUFSIZE]; int nByteRecv;


SOCKADDR_IN from; int fromlen; nByteRecv = recvfrom(s,buf,BUFSIZE,0, (LPSOCKADDR)&from,&fromlen); if(nByteRecv == SOCKET_ERROR ) //

Lp trnh mng Chng 3

117

3.4 Cc hm WinSock (tt)


Hm khai bo nhn event t network cho socket.
int WSAAsyncSelect (SOCKET s, HWND hWnd, unsigned int wMsg, long lEvent); hWnd : ca s nhn s kin. wMsg: thng ip gi n. lEvent : s kin ca socket cn x l. Khi dng hm ny, socket s c chuyn v trng thi nonblocking. i vi mi socket th ch khai bo mt thng ip n. C th khai bo nhiu s kin bng php OR (|)
Lp trnh mng Chng 3 118

3.4 Cc hm WinSock (tt)


V d v hm WSAAsyncSelect BOOL CServerDlg::OnInitDialog() { //s l socket c to, // s dng cc hm bind v listen if(WSAAsyncSelect(s,m_hWnd,WM_USER+1, FD_ACCEPT)==SOCKET_ERROR) { return TRUE; } return FALSE; }
Lp trnh mng Chng 3 119

3.4 Cc hm WinSock (tt)


Sau khi dng hm WSAAsyncSelect, ta phi khai bo hm x l bin c tng ng.
BEGIN_MESSAGE_MAP(CServerDlg, CDialog) //{{AFX_MSG_MAP(CServerDlg) ON_MESSAGE(WM_USER+1,OnAccept) //... //}}AFX_MSG_MAP END_MESSAGE_MAP()

Vit hm x l bin c tng ng


LONG CServerDlg::OnAccept(WPARAM wParam, LPARAM lParam){ }
Lp trnh mng Chng 3 120

3.4 Cc hm WinSock (tt)


C th vit code cho hm WindowProc x l s kin network.
LRESULT CServerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)

Socket desciptor switch (message) { case WM_USER+1 : OnAccept(); return 1; case WSA_RDCLOSE : if (WSAGETSELECTEVENT(lParam) == FD_READ) Read_Process(wParam);
Lp trnh mng Chng 3 121

3.4 Cc hm WinSock (tt)


Hm ng socket :
int closesocket ( SOCKET s); Hm tr v gi tr 0 nu thnh cng, nu tht bi tr v gi tr SOCKET_ERROR

Lp trnh mng Chng 3

122

3.4 Cc hm WinSock (tt)


Lp trnh trn mng trn Windows bng MFC : dng cc lp CWinSock, CDatagramSocket, CStreamSocket. Tham kho thm MSDN

Lp trnh mng Chng 3

123

CHNG 4 LP TRNH MNG VI JAVA


4.1 Gii thiu ngn ng Java 4.2 V d v lp trnh mng bng Java 4.3 Khi nim Stream v Multithreading 4.4 Th vin java.net.*
Lp trnh mng Chng 4 124

4.1 Gii thiu ngn ng Java


L ngn ng lp trnh hng i tng trong sng, ra i vo khong nm 1995 do Sun MicroSystems xy dng. L ngn ng thng dch, chy trn kin trc my o (Java Virtual Machine). H tr mng m lp trnh mng, bo mt, multi-thread S dng th vin chun JDK
Lp trnh mng Chng 4 125

4.1 Gii thiu ngn ng Java


JVM h tr trn nhiu flatform => Java c tnh portable write one-run everywhere. Hin c rt nhiu cng c h tr lp trnh Java nh : JBuilder (5), Visual Caf, Microsoft Visual J++ JDK (Java Development Kit) phin bn mi 1.4.1 trn http://java.sun.com/j2se/1.4.1/index.html
Lp trnh mng Chng 4 126

4.1 Gii thiu ngn ng Java


Ci t : download chng trnh v ci t ln my tnh theo hng dn. VD:
Windows : C:\JDK Unix : /usr/local/jdk

t bin mi trng PATH n th mc BIN trong th mc ci t:


Windows : SET PATH=c:\jdk\bin;%PATH% Unix :
PATH=$PATH:/usr/local/jdk/bin export PATH
Lp trnh mng Chng 4 127

4.1 Gii thiu ngn ng Java


t bin mi trng CLASSPATH n cc package c s dng trong chng trnh. VD:
set CLASSPATH=c:\lib\jdbc.zip;c\lib\xml4j.jar;.

Lp trnh : c th dng trnh son tho bt k, lu vi tn file .java Bin dch :


javac file-name.java

Chy :
java file-name
Lp trnh mng Chng 4 128

4.2 V d LTM vi Java


Chng trnh client/server Echo Chng trnh Client
1. //file Client.java 2. import java.net.*; 3. import java.io.*; 4. public class Client{ 5. public static void main(String args[]) throws Exception{ 6. Socket clientsock; 7. DataOutputStream output; 8. BufferedReader input;//b m c d liu 9. clientsock = new Socket("127.0.0.1",2000); 10. input = new BufferedReader(new 11. InputStreamReader(clientsock.getInputStream())); 12. output = new DataOutputStream( 13. clientsock.getOutputStream());

Lp trnh mng Chng 4

129

4.2 V d (tt)
Chng trnh Client
14. BufferedReader keyInput = new BufferedReader(new 15. InputStreamReader(System.in)); 16. System.out.print("Enter sentence to send to server:"); 17. String data = keyInput.readLine(); 18. output.writeBytes(data+"\n"); 19. int recvByte; 20. System.out.print("Data receicved: "); 21. System.out.println(input.readLine()); 22. clientsock.close(); 23. }//main 24. }//class

Bin dch: javac Client.java Thc thi : java Client


Lp trnh mng Chng 4 130

4.2 V d (tt)
Chng trnh Server
1. //file Server.java 2. import java.net.*; 3. import java.io.*; 4. public class Server{ 5. public static void main(String args[]) throws Exception{ 6. ServerSocket serversock = new ServerSocket(2000); 7. DataOutputStream output;//stream xuat du lieu 8. BufferedReader input;//stream doc du lieu 9. for(;;){ 10. Socket client = serversock.accept(); 11. output = new DataOutputStream( 12. client.getOutputStream());

Lp trnh mng Chng 4

131

4.2 V d (tt)
Chng trnh Server (tt)
13. input = new BufferedReader(new 14. InputStreamReader(client.getInputStream())); 15. String data = input.readLine(); 16. System.out.println("Recv from client: "+data); 17. output.writeBytes(data+"\n"); 18. output.flush(); 19. }//for 20. } //main 21. }//class

Dch : javac Server.java Chy : java Server


Lp trnh mng Chng 4 132

4.3 Stream v Multithreading


Khi nim stream trong ngn ng Java:
Stream : h tr chc nng truy xut I/O trong ngn ng Java. Cc cng vic truy xut I/O c th k n nh file, kt ni mng, bn phm( thit b nhp chun), mn hnh (tb xut chun) Stream l mi trng dn d liu, khng quan tm n nh dng ca d liu Cc lp stream c cung cp gi java.io.*;
Lp trnh mng Chng 4 133

4.3 Stream v Multithreading (tt)


Khi nim stream ...(tt):
c chia ra lm hai loi chnh input stream l stream cha d liu nhp; output stream l stream cha d liu xut. Hai lp c bn trong Java x l nhp xut l InputStream v OutputStream. Cc lp dn xut thng dng ca InputStream : BufferedInputStream, DataInputStream, ByteArrayInputStream, StringBufferInputStream.
Lp trnh mng Chng 4 134

4.3 Stream v Multithreading (tt)


Khi nim stream ...(tt):
Cc lp dn xut thng dng ca OutputStream : BufferedOutputStream, DataOutputStream, ByteArrayOutputStream Cc lp thng dng cho truy xut tp tin : File, RadomAcessFile Chi tit lp trnh xem thm Java docs ca JDK

Lp trnh mng Chng 4

135

4.3 Stream v Multithreading (tt)


Thread v Multithread trong Java.
Thread : l mt i tng c th chy nhiu phin bn ng thi. Java h tr lp trnh thread trong bn thn ngn ng. C hai cch to Thread :
Xy dng class extends Thread. Implements interface Runable

Lp trnh mng Chng 4

136

4.3 Stream v Multithreading (tt)


Multithreading
V d :
public static void main(String args[]){ //... while(true){ Socket newsock = server.accept(); ClientThread ct = new ClientThread(newsock); ct.start(); } }

Lp trnh mng Chng 4

137

4.3 Stream v Multithreading (tt)


class ClientThread extends Thread{ Socket sock; public ClientThread(Socket sock){ this.sock = sock; } public void run(){ //xu ly } }

Lp trnh mng Chng 4

138

4.4 Th vin java.net.*


Lp InetAddress : dng thao tc v a ch Internet, cc phng thc thng dng:
public byte[] getAddress(): Returns the raw IP address of this object public static InetAddress[] getAllByName(String host) throws UnknownHostException public String getHostAddress() Returns the IP address string "%d.%d.%d.%d". public static InetAddress getByName(String host) throws UnknownHostException
Lp trnh mng Chng 4 139

4.4 Th vin java.net.*


Lp Socket : dng cho chng trnh client kt ni n my ch
public Socket(String host, int port) throws UnknownHostException, IOException
Creates a stream socket and connects it to the specified port number on the named host.

public Socket(InetAddress address, int port) throws IOException


Creates a stream socket and connects it to the specified port number at the specified IP address.

public Socket(String host, int port, boolean stream) throws IOException


Creates a stream socket and connects it to the specified port number on the named host.
Lp trnh mng Chng 4 140

4.4 Th vin java.net.*


Lp Socket (tt):
public InputStream getInputStream() throws IOException public InetAddress getInetAddress()
Returns the address to which the socket is connected.

int getPort()
Returns the remote port to which this socket is connected.

public OutputStream getOutputStream() throws IOException


mReturns an output stream for this socket.

Lp trnh mng Chng 4

141

4.4 Th vin java.net.*


Lp ServerSocket : dng cho chng trnh server tao socket v chp nhn kt ni.
ServerSocket(int port)
Creates a server socket on a specified port.

ServerSocket(int port, int backlog)


Creates a server socket and binds it to the specified local port number, with the specified backlog.

ServerSocket(int port, int backlog, InetAddress bindAddr)


Create a server with the specified port, listen backlog, and local IP address to bind to.

Lp trnh mng Chng 4

142

4.4 Th vin java.net.*


Lp ServerSocket (tt)
public Socket accept() throws IOException
Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.

public void close() throws IOException


Closes this socket.

public void setSoTimeout(int timeout) throws SocketException


Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds.

public String toString()


Returns the implementation address and implementation port of this socket as a String.
Lp trnh mng Chng 4 143

4.4 Th vin java.net.*


Lp DatagramSocket : s dng cho chng trnh dng UDP
public DatagramSocket() throws SocketException
Constructs a datagram socket and binds it to any available port on the local host machine.

public DatagramSocket(int port) throws SocketException


Constructs a datagram socket and binds it to the specified port on the local host machine.

public DatagramSocket(int port, InetAddress laddr) throws SocketException


Creates a datagram socket, bound to the specified local address. The local port must be between 0 and 65535 inclusive.

Lp trnh mng Chng 4

144

4.4 Th vin java.net.*


Lp DatagramSocket (tt) :
public void connect(InetAddress address, int port)
Connects the socket to a remote address for this socket.

public void disconnect()


Disconnects the socket. This does nothing if the socket is not connected.

public void receive(DatagramPacket p) throws IOException


Receives a datagram packet from this socket

public void send(DatagramPacket p) throws IOException


Sends a datagram packet from this socket.

Lp trnh mng Chng 4

145

4.4 Th vin java.net.*


Lp DatagramPacket : dng xy dng cc gi tin trao i theo giao thc UDP.
public DatagramPacket(byte[] buf, int length)
Constructs a DatagramPacket for receiving packets of length length.

public DatagramPacket(byte[] buf, int length, InetAddress address, int port)


Constructs a datagram packet for sending packets of length length to the specified port number on the specified host.

public DatagramPacket(byte[] buf, int offset, int length)


Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer

Lp trnh mng Chng 4

146

4.4 Th vin java.net.*


Lp DatagramPacket (tt)
public InetAddress getAddress()
Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received.

public byte[] getData()


Returns the data received or the data to be sent.

public int getLength()


Returns the length of the data to be sent or the length of the data received.

public int getPort()


Returns the port number on the remote host.

Lp trnh mng Chng 4

147

4.4 Th vin java.net.*


Lp DatagramPacket (tt)
public void setAddress(InetAddress iaddr)
Sets the IP address of the machine to which this datagram is being sent.

public void setPort(int iport)


Sets the port number on the remote host to which this datagram is being sent.

public void setData(byte[] buf)


Set the data buffer for this packet.

public void setData(byte[] buf, int offset, int length)


Set the data buffer for this packet.
Lp trnh mng Chng 4 148

4.4 Th vin java.net.*


Lp URL : kt ni n mt ti nguyn Internet.
public URL(String spec) throws MalformedURLException
Creates a URL object from the String representation.

public URL(String protocol, String host, String file) throws MalformedURLException


Creates a URL from the specified protocol name, host name, and file name. The default port for the specified protocol is used.

public URL(String protocol, String host, int port, String file) throws MalformedURLException
Creates a URL object from the specified protocol, host, port number, and file. Specifying a port number of -1 indicates that the URL should use the default port for the protocol.

Lp trnh mng Chng 4

149

4.4 Th vin java.net.*


Lp URL(tt)
public final Object getContent() throws IOException
Returns the contents of this URL.

public String getFile()


Returns the file name of this URL.

public URLConnection openConnection() throws IOException


Returns a URLConnection object that represents a connection to the remote object referred to by the URL.

public final InputStream openStream() throws IOException


Opens a connection to this URL and returns an InputStream for reading from that connection.
Lp trnh mng Chng 4 150

You might also like