Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 44

Lp trnh Socket vi

Java

Network Programming

Ni dung bi hc

Gii thiu gi java.net


Lp InetAddress
Truyn tin vi giao thc TCP

TCP Sockets
V d v my ch/khch TCP

Truyn tin vi giao thc UDP

Datagram Sockets
V d v my ch/khch UDP
Network Programming

Cc classes trong gi java.net

Gi java.net cha cc classes cho php thc


hin lp trnh mng

InetAddress:

ServerSocket:

biu din gi tin UDP

DatagramSocket:

Socket kt ni

DatagramPacket:

Socket ch pha my ch

Socket

nh x, chuyn i v trnh din a ch IP

giao din socket gi v nhn gi tin UDP

MulticastSocket:

giao din socket gi v nhn cc gi tin multicast


Network Programming

Cc classes trong gi java.net


(2)

URL

Locator)
URLConnection

Biu din kt ni gia vi my ch biu din bi URL

URLEncoder & URLDecoder

Biu din ti nguyn m t bi URL(Uniform Resource

Chuyn i biu din d liu vi cc m d liu khc


nhau

ContentHandler:

t ng cp nht phn mm x l cc kiu d liu mi


t dng
Network Programming

Exceptions in Java

BindException
ConnectException
MalformedURLException
NoRouteToHostException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException
Network Programming

Trnh din a ch IP
- Lp InetAddress

Khi to i tng InetAddress

public static InetAddress getByName(String host)


throws UnknownHostException
public static InetAddress[] getAllByName(String host)
throws UnknownHostException
public static InetAddress getLocalHost() throws
UnknownHostException
Kt ni n chng trnh DNS cc b ly thng tin

C th gy ra ngoi l nu kt ni khng c php


C th t ng kt ni vi bn ngoi

C th b li dng truyn tin tri php ra ngoi qua DNS

Network Programming

Trnh din a ch IP
- Lp InetAddress (2)

Tr v tn min trong i tng InetAddress

public String getHostName()

Tr v a ch IP dng chui k t/chui byte

public String getHostAddress()


public byte[] getAddress()

Dng xc nh kiu a ch IP (IPv4/IPv6)


Cn chuyn i biu din byte sang int

int unsignedByte = signedByte < 0 ? signedByte + 256 : signedByte;

Xc nh kiu a ch

public boolean isMulticastAddress()


public boolean isLoopbackAddress( )

Mt s hm khc

public int
hashCode()
public boolean equals(Object obj)

i tng obj bng mt i tng InetAddress khi n l mt phin bn


(instance) InetAddress v c cng a ch IP

public String toString()


Network Programming

import java.net.*;
import java.io.*;
public class IPFinder
{
public static void main(String[] args) throws IOException
{
String host;
BufferedReader input =
new BufferedReader(
new InputStreamReader(System.in));

System.out.print("\n\nEnter host name: ");


host = input.readLine(); /*c chui k t nhp t bn phm*/
try
{
InetAddress address = InetAddress.getByName(host);
System.out.println("IP address: " + address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Could not find " + host);
}
}

Network Programming

Ly a ch ca my ch
import java.net.*;
public class MyLocalIPAddress
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println (address.toString());
}
catch (UnknownHostException e)
{
System.out.println("Could not find local address!");
}
}
}

Network Programming

Truyn tin vi giao thc TCP


TCP server
TCP client
ServerSocket ()

Connection
request

Socket()
OutputStream.
write()

InputStream.
read()
Socket.close()

data (request)

ServerSocket.
accept()

InputStream.
read()
Process request

data (reply)
EOF

OutputStream.
write()

Wait next
request

InputStream.
read()
ServerSocket.
close()

Network Programming

10

Lp trnh my khch TCPLp Java.net.Socket


Cc bc thit lp my khch

To i tng Socket thit lp kt ni n my


ch s dng Socket()
Thit lp cc dng xut/nhp d liu
Gi v nhn d liu
ng kt ni close()

Network Programming

11

Lp trnh my khch TCP


Lp Java.net.Socket

Lp c bn ca Java thc hin truyn tin TCP


gia my khch v my ch

Thit lp hoc ngt kt ni v thit lp cc ty chn socket

Kt ni c thit lp khi khi to i tng

Mi i tng Socket c gn vi mt my ch duy nht


public Socket(String host, int port) throws
UnknownHostException, IOException
public Socket(InetAddress address, int port) throws IOException
public Socket(String host, int port, InetAddress localAddress, int
localPort) throws IOException
public Socket(InetAddress address, int port, InetAddress
localAddress, int localPort) throws IOException

Network Programming

12

The Java.net.Socket Class


Ly thng tin v mt
Socket

Ly thng tin v a ch my tnh kt ni n


public InetAddress getInetAddress( )

Ly thng tin cng kt ni n


public int getPort( )

Ly thng tin v cng kt ni cc b


public int getLocalPort( )

Ly thng tin v a ch kt ni cc b
public InetAddress getLocalAddress( )

Network Programming

13

The Java.net.Socket Class


Xut nhp d liu socket

Gi v nhn d liu socket c thc hin


thng qua dng d liu xut/nhp

public InputStream getInputStream()


throws IOException

tr v i tng InputStream

public OutputStream getOutputStream()


throws IOException

tr v i tng OutputStream

Network Programming

14

Lp InputStream

Cung cp cc hm c d liu dng byte


public abstract int read( ) throws IOException
public int read(byte[] input) throws IOException
public int read(byte[] input, int offset, int length) throws
IOException
public int available( ) throws IOException

Gi tr tr v bng -1 nu n cui dng d liu


D liu c di dng signed byte

Cn chuyn i signed byte -> unsigned byte


b = in.read( );
int i = b >= 0 ? b : 256 + b;

Thc hin vng lp c ht d liu

Network Programming

15

V d v c d liu
int bytesRead = 0;
int bytesToRead = 1024;
byte[] input = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
bytesRead += in.read(input, bytesRead, bytesToRead-bytesRead);
}

int bytesRead = 0;
int bytesToRead = 1024;
byte[] input = new byte[bytesToRead];
while (bytesRead < bytesToRead) {
int result = in.read(input, bytesRead, bytesToRead - bytesRead);
if (result == -1) break;
bytesRead += result;
}
Network Programming

16

Lp OutputStream

Cung cp cc hm ghi d liu


public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length)
throws IOException
public void flush( ) throws IOException
public void close( ) throws IOException

Ghi mt dy byte hiu qu hn ghi tng byte


Nn s dng hm flush() lnh ghi c thc
hin ngay
Network Programming

17

Filter Streams

InputStream v OutputStream
l cc lp x l d liu th
(byte)

Cn chuyn i d liu th
sang cc nh dng d liu
nht nh v ngc li

7-bit ASCII, 8-bit Latin-1 hay


UTF-8, nh dng zip

Hai loi filter

filter stream: lm vic trn d


liu byte
readers and writers: lm vic x
l d liu text vi cc kiu
encoding khc nhau

Application

text
InputStreamReader
buffered data
GZIPInputStream
buffered compressed data
CipherInputStream
buffered compressed encrypted data
BufferedInputStream
raw compressed encrypted data
InputStream

Network Programming

raw compressed encrypted data

Network
18

The Java.net.Socket Class


ng socket

public void close() throws IOException


public void shutdownInput( ) throws
IOException // Java 1.3
public void shutdownOutput( ) throws
IOException // Java 1.3
public boolean isInputShutdown( ) // Java 1.4
public boolean isOutputShutdown( ) // Java 1.4

Network Programming

19

V d: DaytimeClient.java
import java.net.*;
import java.io.*;
public class DaytimeClient {
public static void main(String[] args) {
String hostname;
int port;
if (args.length > 0) {
hostname = args[0];
port = Integer.parseInt(args[1]);
}
else {
hostname = "time.nist.gov";
port = 13;
}

Network Programming

20

Example: DaytimeClient.java
(2)
try {
Socket theSocket = new Socket(hostname, port);
InputStream timeStream = theSocket.getInputStream( );
StringBuffer time = new StringBuffer( );
int c;
while ((c = timeStream.read( )) != -1)
time.append((char) c);
String timeString = time.toString( ).trim( );
System.out.println("It is " + timeString + " at " + hostname);
} // end try
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
}
} // end main
} // end DaytimeClient

Network Programming

21

Thit lp ty chn socket

TCP_NODELAY
public void setTcpNoDelay(boolean on) throws SocketException
public boolean getTcpNoDelay( ) throws SocketException

SO_REUSEADDR // Java 1.4


public void setReuseAddress(boolean on) throws SocketException
public boolean getReuseAddress( ) throws SocketException

SO_TIMEOUT
public void setSoTimeout(int milliseconds) throws SocketException
Public int getSoTimeout( ) throws SocketException

SO_LINGER
public void setSoLinger(boolean on, int seconds) throws SocketException
public int getSoLinger( ) throws SocketException

SO_SNDBUF/ SO_RCVBUF (Java 1.2 and later)


public void setReceiveBufferSize(int size) throws SocketException, IllegalArgumentException
public int getReceiveBufferSize( ) throws SocketException

SO_KEEPALIVE (Java 1.3 and later)


public void setKeepAlive(boolean on) throws SocketException
public boolean getKeepAlive( ) throws SocketException

Network Programming

22

Lp trnh my ch TCPLp Java.net.ServerSocket

Cc bc thit lp my ch
1.

2.

To mt i tng ServerSocket s dng hm


khi to ServerSocket( )
ServerSocket ch kt ni t pha my khch
bng hm accept()

3.
4.
5.

Tr v mt i tng Socket kt ni gia my khch


v my ch

Thit lp cc dng xut/nhp d liu


Gi v nhn d liu
ng kt ni
Network Programming

23

Lp Java.net.ServerSocket

C bn hm khi to ServerSocket cho php thit lp


cng, kch thc hng i ca cc yu cu kt ni v
network interface gn cho tin trnh my ch

public ServerSocket(int port) throws BindException, IOException

public ServerSocket(int port, int backlog) throws BindException,


IOException
public ServerSocket(int port, int backlog, InetAddress bindAddr)
throws BindException, IOException
public ServerSocket( ) throws IOException // Java 1.4

Network Programming

24

Lp Java.net.ServerSocket - Chp
nhn v ng kt ni

public Socket accept() throws IOException

Dng thc hin ca tin trnh v i kt ni t


my khch
Khi c mt my khch kt ni n, hm accept( )
s tr v mt i tng kiu Socket
Ch x l cc loi ngoi l khc nhau

public void close() throws IOException

ng socket my ch v gii phng cng ch

Network Programming

25

V d v my ch
DaytimeServer
import java.net.*;
import java.io.*;
import java.util.Date;

public class DaytimeServer {


public final static int DEFAULT_PORT = 13;
public static void main(String[] args) {
int port = DEFAULT_PORT;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
if (port < 0 || port >= 65536) {
System.out.println("Port must between 0 and 65535");
return;
}
}
catch (NumberFormatException ex) {
// use default port
}
}

Network Programming

26

try {
ServerSocket server = new ServerSocket(port);
Socket connection = null;
while (true) {
try {
connection = server.accept( );
Writer out = new OutputStreamWriter(connection.getOutputStream( ));
Date now = new Date( );
out.write(now.toString( ) +"\r\n");
out.flush( );
connection.close( );
}
catch (IOException ex) {}
finally {
try {
if (connection != null) connection.close( );
}
catch (IOException ex) {}
}
} // end while
} // end try
catch (IOException ex) {
System.err.println(ex);
} // end catch

} // end main
} // end DaytimeServer

Network Programming

27

Lp Java.net.ServerSocket Ly
thng tin v socket

public InetAddress getInetAddress( )


public int getLocalPort( )

Network Programming

28

Lp Java.net.ServerSocket Ty

bin socket

SO_TIMEOUT
public void setSoTimeout(int timeout) throws SocketException
public int getSoTimeout( ) throws IOException

SO_REUSEADDR
public void setReuseAddress(boolean on) throws SocketException
public boolean getReuseAddress( ) throws SocketException

SO_RCVBUF
public void setReceiveBufferSize(int size) throws SocketException,
IllegalArgumentException
public int getReceiveBufferSize( ) throws SocketException

Network Programming

29

Truyn tin vi giao thc UDP

Network Programming

30

Lp java.net.DatagramPacket

Biu din cc gi d liu UDP


Cung cp cc hm

Ly v thit lp a ch ch/ngun t/vo tiu IP


Ly v thit lp cng giao tip ch/ngun
Nhn v thit lp gi d liu UDP

Network Programming

31

Hm khi to
DatagramPacket
Vi bn nhn:
DatagramPacket(byte[] buf, int len);
Vi bn gi:
DatagramPacket( byte[] buf, int len
InetAddress a, int port);

Network Programming

32

Cc hm DatagramPacket
byte[] getData();
void setData(byte[] buf);

a ch ch

void setAddress(InetAddress a);


void setPort(int port);
InetAddress getAddress();
int getPort();

C th l a
ch/cng ngun/ch

Network Programming

33

Lp DatagramSocket

To datagram socket nhn DatagramPacket.

Khng c phn bit gia socket my khch v socket


my ch
Mt DatagramSocket c th gi cho nhiu a ch ch
khc nhau.

a ch ch c lu ti DatagramPacket

public DatagramSocket() throws SocketException


public DatagramSocket(int port) throws SocketException
public DatagramSocket(int port, InetAddress laddr) throws
SocketException

Network Programming

34

Lp DatagramSocket

Gi v nhn gi d liu UDP

public void send(DatagramPacket dp) throws IOException


Gi gi d liu UDP vi i tng kiu DatagramPacket c
to ra

public void receive(DatagramPacket dp) throws IOException

public void close( )

Gii phng cng ang oc s dng bi socket

public int getLocalPort( )

Nhn gi d liu UDP v lu li ti i tng kiu


DatagramPacket c to ra t trc

Tr v s hiu cng m socket ang s dng

public InetAddress getLocalAddress( )

Tr v a ch IP m socket ang s dng


Network Programming

35

iu khin kt ni vi Java
1.2

public void connect(InetAddress host, int port)

Gi v nhn gi tin t mt i ch IP v cng c nh trc


Khng ging nh kt ni TCP

public void disconnect( )


public int getPort( )
public InetAddress getInetAddress( )
public InetAddress getRemoteSocketAddress( ) // Java 1.4

Network Programming

36

Cc bc thit lp truyn tin UDP - MY


CH
1.

2.

3.

4.

Khi to mt i tng kiu DatagramSocket


DatagramSocket dgramSocket =
new DatagramSocket(1234);
To buffer cho dng d liu nhp
byte[] buffer = new byte[256];
To i tng kiu DatagramPacket cho dng d liu nhp
DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
Ch dng d liu nhp
dgramSocket.receive(inPacket)

Network Programming

37

Cc bc thit lp truyn tin UDP - MY


CH(2)
5.

6.

7.

Ly a ch v cng ca bn gi t gi tin nhn c


InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();
Ly d liu t buffer
string message =
new String(inPacket.getData(), 0, inPacket.getLength());
To gi d liu UDP xut

DatagramPacket outPacket =
new DatagramPacket(
response.getBytes(), response.length(),
clientAddress, clientPort);
8.

9.

Gi gi d liu
dgramSocket.send(outPacket)
ng DatagramSocket:
dgramSocket.close();
Network Programming

38

Cc bc thit lp truyn tin UDP


My khch
(1)To i tng kiu DatagramSocket

1.

2.

3.

4.

DatagramSocket dgramSocket = new DatagramSocket;


To gi d liu UDP xut
DatagramPacket outPacket = new DatagramPacket(
message.getBytes(),
message.length(),
host, port);
Gi gi d liu
dgramSocket.send(outPacket)
To buffer cho d liu nhp
byte[] buffer = new byte[256];

Network Programming

39

Cc bc thit lp truyn tin UDP


My khch (2)
5.

6.

7.

8.

To i tng kiu DatagramPacket cho gi d liu nhp


DatagramPacket inPacket =
new DatagramPacket(buffer, buffer.length);
Nhn gi d liu nhp
dgramSocket.receive(inPacket)
Ly d liu t buffer
string response = new String(inPacket.getData(), 0,
inPacket.getLength());
ng DatagramSocket:
dgramSocket.close();

Network Programming

40

V d v my ch UDP
import java.net.*;
import java.io.*;
public class UDPDiscardServer {
public final static int DEFAULT_PORT = 9;
public final static int MAX_PACKET_SIZE = 65507;
public static void main(String[] args) {
int port = DEFAULT_PORT;
byte[] buffer = new byte[MAX_PACKET_SIZE];
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
// use default port
}

Network Programming

41

V d v my ch UDP(2)
try {
DatagramSocket server = new DatagramSocket(port);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
try {
server.receive(packet);
String s = new String(packet.getData( ), 0, packet.getLength( ));
System.out.println(packet.getAddress( ) + " at port "
+ packet.getPort( ) + " says " +
s);
//
packet.setLength(buffer.length); // reset the length for the next packet
}
catch (IOException ex) {
System.err.println(ex);
}
} // end while
} // end try
catch (SocketException ex) {
System.err.println(ex);
} // end catch
} // end main
}

Network Programming

42

V d v my khchUDP
import java.net.*;
import java.io.*;
public class UDPDiscardClient {
public final static int DEFAULT_PORT = 9;
public static void main(String[] args) {
String hostname;
int port = DEFAULT_PORT;
if (args.length > 0) {
hostname = args[0];
try {
port = Integer.parseInt(args[1]);
}
catch (Exception ex) {
// use default port
}
}
else {
hostname = "localhost";
}

Network Programming

43

V d v my khch UDP(2)
try {
InetAddress server = InetAddress.getByName(hostname);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket theSocket = new DatagramSocket( );
while (true) {
String theLine = userInput.readLine( );
if (theLine.equals(".")) break;
byte[] data = theLine.getBytes( );
DatagramPacket theOutput = new DatagramPacket(data, data.length, server, port);
theSocket.send(theOutput);
} // end while
} // end try
catch (UnknownHostException uhex) {
System.err.println(uhex);
}
catch (SocketException socex) {
System.err.println(socex);
}
catch (IOException ioex) {
System.err.println(ioex);
}
} // end main
}

Network Programming

44

You might also like