java sockets white - columbia university · 1 java sockets alexander v. konstantinou cs4119 –...
TRANSCRIPT
11
Java
Soc
kets
Ale
xand
er V
. Kon
stan
tinou
CS
4119
–C
ompu
ter
Net
wor
ksC
olum
bia
Uni
vers
ityS
prin
g 20
03
22
Coo
rdin
ates
TC
P, U
DP
IP
Eth
erne
t
SS
L
CO
RB
A, R
MI
App
licat
ion
IP
Eth
erne
t
TC
P, U
DP
IP
Eth
erne
t
SS
L
CO
RB
A, R
MI
App
licat
ion
App
licat
ion
Laye
r
Tra
nspo
rtLa
yer
Inte
rnet
Laye
r
Net
wor
kA
cces
sLa
yer
Soc
kets
Soc
kets
HT
TP
, FT
P, D
NS
, SM
TP
rem
oteO
bjec
t.met
hod(
arg)
33
Wha
t Are
Soc
kets
?
•P
rogr
amm
ing
abst
ract
ion
(AP
I)–
Equ
ival
ent:
File
I/O
AP
I
•N
etw
ork
serv
ice
end-
poin
t
•O
rigin
ated
as
BS
D U
NIX
con
cept
–N
ow p
art o
f mod
ern
OS
& la
ngua
ges
WW
WB
row
ser
OS
Net
wo
rkS
tack
Inte
rnet
Net
wor
kS
ervi
ceN
etw
ork
Clie
nt
AP
IP
roto
col
IP
44
File
vs.
Soc
ket A
PI
clos
e()
clos
e()
writ
e(by
tes)
writ
e(by
tes)
read
(byt
es)
read
(byt
es)
open
(des
tinat
ion)
st
ream
open
(file
nam
e)
stre
am
Net
wo
rkF
ile
Filef = new File("test");
FileInputStreamfis= new FileInputStream(f);
char c = fis.read();
fis.close();
Socket
s = new Socket("www.cs.columbia.edu", 80);
InputStreamis = s.getInputStream();
char c = is.read();
s.close();
55
Soc
ket T
ypes
•S
trea
min
gso
cket
s–
Poi
nt-t
o-po
int
–C
onne
ctio
n ba
sed
•B
i-dire
ctio
nal
–R
elia
ble,
in-o
rder
(F
IFO
)
•D
atag
ram
sock
ets
–P
oint
-to-
{poi
nt |
mul
tipoi
nt}
–C
onne
ctio
nles
s–
Non
-rel
iabl
e–
Out
-of-
orde
r de
liver
y–
Lim
ited
payl
oad
X
X
stre
am
buffe
r
66
Soc
kets
Adv
anta
ges
•C
omm
on p
rogr
amm
ing
abst
ract
ion
–S
epar
ate
the
netw
orki
ng s
tack
•A
pplic
atio
n fle
xibi
lity
–S
SL
inst
ead
of v
anill
a T
CP
–Lo
ggin
g &
per
form
ance
mea
sure
men
ts–
Tun
nelin
g
TC
PS
SL
http
brow
ser
http
sbr
owse
r
77
Java
Soc
ket A
PI O
verv
iew
Pro
toco
lT
ype
Cla
ss
TC
P s
erve
rS
trea
mja
va.n
et.S
erve
rSoc
ket
UD
P c
lient
/ser
ver
Dat
agra
mja
va.n
et.D
atag
ram
Soc
ket
SS
L cl
ient
Str
eam
java
x.ne
t.ssl
.SS
LSoc
ket
SS
L se
rver
Str
eam
java
x.ne
t.ssl
.SS
LSer
verS
ocke
t
TC
P c
lient
Str
eam
java
.net
.Soc
ket
88
Java
I/O
Str
eam
s
sock
et
Inpu
tStr
eam
/ Out
putS
trea
m
IPIP
IP
Buf
fere
d{In
put,O
utpu
t}S
trea
m
…7
4 5
6 1
3 0
…
…7
4 5
6 1
3 0
…
OS
OS
Dat
a{In
put,O
utpu
t}S
trea
m
Obj
ect{
Inpu
t, O
utpu
t)S
trea
m
{ id
=1,
des
cr=
“tes
t”}
123
“abc
”10
.1
File
I/O
File
I/O
99
Net
wor
k C
omm
unic
atio
n
•B
yte-
base
d–
Byt
e-st
ream
or
byte
-arr
ay
•P
roto
col t
ypes
–T
ext-
base
d: H
TT
P, S
MT
P, S
OA
P, …
–B
it-ba
sed:
DN
S, L
DA
P, S
NM
P …
•Is
sues
–T
ext:
enco
ding
(U
nico
de 1
6bit
8bit)
–B
it: b
yte
orde
ring
(littl
e/bi
g en
dian
)
1010
Net
wor
k P
orts
•In
tern
et h
ost a
ddre
ss–
Exa
mpl
e: 1
28.5
9.16
.1
•H
ow to
offe
r m
ultip
le s
ervi
ces?
–M
ailb
ox a
ppro
ach
–P
ort n
umbe
r ad
dres
sing
[1-6
5535
] (21
6 )–
Exa
mpl
e: 1
28.5
9.16
.1:T
CP
:80
IP H
ost
TC
P:8
0
TC
P:2
312
8.59
.16.
20
UD
P:5
3
http
d
nam
ed
teln
etd
Inte
rnet
1111
Exa
mpl
e: H
TT
P C
lient
:Bro
wse
r:W
WW
Ser
ver
TC
P C
on
nec
t
“GE
T /”
CR
CF
“CO
NT
EN
T-T
YP
E=t
ext/
htm
l CO
NT
EN
T-L
EN
GT
H=1
22 …
”
•T
rivia
l HT
TP
1.0
Clie
nt–
App
licat
ion-
laye
r pr
otoc
ol o
ver
TC
P
–T
ext-
base
d pr
otoc
ol
1212
HT
TP
Clie
nt (
No
Err
or H
andl
ing)
Socket
socket= new Socket(“www.cs.columbia.edu”, 80);
BufferedOutputStreamostream=
new BufferedOutputStream(socket.getOutputStream());
byte[] request = “GET /\r\n”.getBytes("ISO-8859-1");
ostream.write(request);
ostream.flush();
BufferedInputStreamistream=
new BufferedInputStream(socket.getInputStream());
byte[] buffer = new byte[4096];
intcount = istream.read(buffer);
while(count!= -1) {
System.out.print(newString(buffer, 0, count));
count = istream.read(buffer);
} socket.close();
1313
Str
eam
Soc
ket E
rror
Han
dlin
g
Socket
socket= null;
try {
socket = new Socket(“www.cs.columbia.edu”, 80);
// Perform I/O
} catch (Throwablee) {
// Application-specific error recovery
} finally{
socket.close();
}•N
etw
orks
fail!
–A
pplic
atio
ns m
ust b
e aw
are
of fa
ilure
s
•S
ocke
ts a
re s
carc
e O
S r
esou
rces
–D
on’t
rely
on
garb
age
colle
ctio
n; c
lose
() w
hen
done
!
1414
Ser
ver
Str
eam
Soc
kets
•B
ind
to p
ort (
e.g.
80)
•W
ait f
or in
com
ing
TC
P c
onne
ctio
n–
Enc
apsu
late
req
uest
as
Soc
keto
bjec
t–
Soc
ket p
air
now
com
mun
icat
e
Soc
ket
Ser
ver
Soc
ket
1. C
onne
ctne
w S
ocke
t(se
rver
, por
t)
Soc
ket
2. C
reat
e(r
etur
n to
acc
ept(
))
3. S
trea
m(b
idire
ctio
nal,
asym
met
ric)
clie
ntse
rver
1515
HT
TP
Ser
ver
(Triv
ial)
ServerSocket
server = new ServerSocket(8080);
while(active) {
Socketsocket= server.accept();
BufferedReaderreader = new BufferedReader
(new InputStreamReader
(new BufferedInputStream(socket.getInputStream())));
String request = reader.readLine();
BufferedOutputStreamostream=
new BufferedOutputStream(socket.getOutputStream());
ostream.write(“HTTP/1.0 404 HTTP NOT FOUND\r\n”);
ostream.flush();
socket.close();
} server.close();
1616
Java
Thr
eads
•W
hy p
aral
leliz
e?
–P
reve
nt b
lock
ing
from
mal
form
ed r
eque
sts
–D
eal w
ith w
ritin
g to
slo
w c
lient
s–
Inte
rleav
e pr
oces
sing
/file
rea
ding
•H
ow?
–M
ultip
le th
read
s
–S
hare
d m
emor
y–
Inte
rleav
ed e
xecu
tion
1717
Thr
eade
d S
erve
r P
atte
rnServerSocket
server =
new ServerSocket(80);
while(isActive) {
Socketsocket=
server.accept();
Handlerhandler
=new Handler(socket);
handler.start();
}
public class Handler
extendsThread{
protected final Socketsocket;
public Handler(Socketsocket) {
this.socket= socket;
} public void run() {
try {
// Protocol Impl.
} finally {
socket.close();
}}
}
1818
Dat
agra
m S
ocke
ts
•C
onne
ctio
nles
s
•U
nrel
iabl
e•
Lim
ited
payl
oad
–T
heor
etic
al 6
5508
byt
es–
Pra
ctic
al 5
12 b
ytes
(IE
TF
RF
C)
•W
hen
to u
se–
Sim
ple
requ
est-
resp
onse
pro
toco
l–
Sm
all r
eque
sts/
repl
ies
(fit
in d
atag
ram
)–
Sta
tele
ss/r
e-en
tran
t ser
vers
–R
eal-t
ime
stre
amin
g
Fra
gmen
tatio
n
1919
UD
P C
lient
Exa
mpl
eDatagramSocketsocket = new DatagramSocket();
byte[] data = "hello world".getBytes();
DatagramPacketpacket = new DatagramPacket
(data,
data.length,
InetAddress.getByName("localhost"),
1234);
socket.send(packet);
data = "followupcall".getBytes();
packet.setData(data);
socket.send(packet);
2020
UD
P S
erve
r E
xam
ple
DatagramSocketsocket = new DatagramSocket(1234);
byte[] buffer = new byte[512];
DatagramPacketpacket =
new DatagramPacket(buffer, buffer.length);
while(true) {
socket.receive(packet);
String msg=
new String(packet.getData(), 0, packet.getLength()));
System.out.println(newjava.util.Date() + ": " + msg);
packet.setLength(buffer.length); // !!! Necessary !!!
}
2121
Mul
ticas
t
•O
ne-t
o-m
any
tran
smis
sion
–S
peci
al r
ange
of I
P a
ddre
sses
•22
4.0.
0.0
–23
9.25
5.25
5.25
5
•S
ame
sock
et A
PI a
s U
DP
•N
ot u
nive
rsal
ly a
vaila
ble
2222
SS
L S
ocke
ts
•S
ecur
e co
mm
unic
atio
ns–
Laye
red
over
TC
P
•D
rop-
in r
epla
cem
ent (
subc
lass
es)
–S
ocke
t S
SLS
ocke
t–
Ser
verS
ocke
tS
SLS
erve
rSoc
ket
•K
ey m
anag
emen
t–keytool
com
man
d-lin
e ut
ility
–C
reat
es p
ublic
/priv
ate
keys
•S
tore
d in
“ke
ysto
res”
–Ja
va V
M in
voca
tion
with
key
stor
ein
fo
2323
Non
-Blo
ckin
g Ja
va I/
O
•T
hrea
d sc
alin
g is
sues
–E
.g. H
TT
P s
erve
r w
ith 1
000s
con
nect
ions
•JD
K 1
.4 in
trod
uced
non
-blo
ckin
g I/O
–P
erfo
rm a
ll pr
oces
sing
in o
ne th
read
–ja
va.n
io.*
pac
kage
2424
Soc
ket F
AQ
s
•W
rong
hos
t/por
t/pro
toco
l–
E.g
“loca
lhos
t”, “
127.
0.0.
1”, “
ww
w”
vs. “
ww
w.fo
o.co
m”
•Ig
norin
g I/O
exc
eptio
ns
•S
trea
ms:
–flu
sh()
whe
n do
ne–
use
buffe
red
read
er/s
trea
m–
clos
e co
nnec
tions
whe
n do
ne
•D
atag
ram
s–
pack
et.s
etLe
ngth
() b
efor
e re
use
–T
est i
n lo
ssy
envi
ronm
ent
2525
Soc
ket F
AQ
s(2
)
•W
ait-
fore
ver
–U
se S
ocke
t.set
SoT
imeo
ut()
–C
atch
Inte
rrup
tedI
OE
xcep
tion
•B
yte-
alig
nmen
t iss
ues
–N
etw
ork
byte
ord
er
•S
ecur
ity r
estr
ictio
ns (
appl
ets)
•U
nix
rest
ricts
non
-roo
t ser
vers
to p
orts
>10
24
2626
Adv
ance
d Is
sues
•T
hrea
d po
ols
–R
esou
rce
man
agem
ent
•B
indi
ng to
spe
cific
inte
rfac
es–
Bin
ding
to a
spe
cific
inte
rfac
e (s
ecur
ity)
•S
win
g ap
plic
atio
ns–
Sw
ing
is s
ingl
e th
read
ed
–N
etw
ork
oper
atio
ns in
non
-Sw
ing
thre
ad–
Use
Sw
ingU
tiliti
es.in
voke
Late
r()