Professional Documents
Culture Documents
Bai 3 - Lap Trinh Socket Voi Java
Bai 3 - Lap Trinh Socket Voi Java
Java
Network Programming
Ni dung bi hc
TCP Sockets
V d v my ch/khch TCP
Datagram Sockets
V d v my ch/khch UDP
Network Programming
InetAddress:
ServerSocket:
DatagramSocket:
Socket kt ni
DatagramPacket:
Socket ch pha my ch
Socket
MulticastSocket:
URL
Locator)
URLConnection
ContentHandler:
Exceptions in Java
BindException
ConnectException
MalformedURLException
NoRouteToHostException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException
Network Programming
Trnh din a ch IP
- Lp InetAddress
Network Programming
Trnh din a ch IP
- Lp InetAddress (2)
Xc nh kiu a ch
Mt s hm khc
public int
hashCode()
public boolean equals(Object obj)
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));
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
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
Network Programming
11
Network Programming
12
Ly thng tin v a ch kt ni cc b
public InetAddress getLocalAddress( )
Network Programming
13
tr v i tng InputStream
tr v i tng OutputStream
Network Programming
14
Lp InputStream
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
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
Application
text
InputStreamReader
buffered data
GZIPInputStream
buffered compressed data
CipherInputStream
buffered compressed encrypted data
BufferedInputStream
raw compressed encrypted data
InputStream
Network Programming
Network
18
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
TCP_NODELAY
public void setTcpNoDelay(boolean on) throws SocketException
public boolean getTcpNoDelay( ) 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
Network Programming
22
Cc bc thit lp my ch
1.
2.
3.
4.
5.
23
Lp Java.net.ServerSocket
Network Programming
24
Lp Java.net.ServerSocket - Chp
nhn v ng kt ni
Network Programming
25
V d v my ch
DaytimeServer
import java.net.*;
import java.io.*;
import java.util.Date;
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
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
Network Programming
30
Lp java.net.DatagramPacket
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
C th l a
ch/cng ngun/ch
Network Programming
33
Lp DatagramSocket
a ch ch c lu ti DatagramPacket
Network Programming
34
Lp DatagramSocket
35
iu khin kt ni vi Java
1.2
Network Programming
36
2.
3.
4.
Network Programming
37
6.
7.
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
1.
2.
3.
4.
Network Programming
39
6.
7.
8.
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