Professional Documents
Culture Documents
Ni dung bi hc
Network Programming
Network Programming
Exceptions in Java
BindException ConnectException MalformedURLException NoRouteToHostException ProtocolException SocketException UnknownHostException UnknownServiceException
3
Network Programming
Network Programming
Lp InetAddress
public static InetAddress getByName(String host) throws UnknownHostException /* tr v chui i tng kiu InetAddress*/ public static InetAddress[] getAllByName(String host) throws UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException public boolean isMulticastAddress() public String getHostName() /*tr v tn min*/ public byte[] getAddress() /*tr v a ch IP dng chui byte*/ public String getHostAddress() /*tr v a ch IP dng k t*/ public int hashCode() public boolean equals(Object obj) 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
12/6/2007
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!"); } } }
connect()
write()
BufferedReader. readLine() Process request PrintWriter. println() BufferedReader. readLine() ServerSocket. close()
read()
data (reply)
EOF
close()
Network Programming
Network Programming
Lp Java.net.Socket
Lp c bnca Java thc hin truyn tin TCP pha my khch Kt ni c thit lp khi khi to i tng
Thit lp hoc ngt kt ni v thit lp cc ty chn socket Mi i tng Socket c gn vi mt my ch duy nht kt ni vi mt my ch khc, phi to ra mt i tng Socket mi
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
ng socket:
Network Programming
Network Programming
10
TCP Sockets
MY KHCH: 1. Thit lp kt ni n my ch
Socket link = new Socket(inetAddress.getLocalHost(),1234);
2. 3. 4.
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
11
Network Programming
12
12/6/2007
Lp Java.net.ServerSocket
Lp java.net.ServerSocket bao gm
Cc hm khi to i tng ServerSocket Cc hm ch kt ni Cc hm thit lp cc loi ty chn socket my ch Cc hm thng dng khc nh toString( )
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 IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException public ServerSocket( ) throws IOException // Java 1.4
Network Programming
13
Network Programming
14
TCP Sockets
MY CH: 1. To mt i tng ServerSocket
ServerSocket servSocket = new ServerSocket(1234);
2.
3. 4.
5.
a my ch vo trng thi ch Socket link = servSocket.accept(); Thit lp cc dng xut/nhp d liu Gi v nhn d liu out.println(awaiting data); String input = in.readLine(); ng kt ni link.close()
Network Programming
Network Programming
15
16
V d v my ch TCP Echo
import java.net.*; import java.io.*; // need this for InetAddress, Socket, ServerSocket // need this for I/O stuff public class TCPEchoServer { static final int BUFSIZE=1024; // define a constant used as size of buffer static public void main(String args[]) { if (args.length != 1) { throw new IllegalArgumentException("Must specify a port!"); } int port = Integer.parseInt(args[0]); try { ServerSocket ss = new ServerSocket(port); // Create Server Socket (passive socket) while (true) { Socket s = ss.accept(); handleClient(s); } } catch (IOException e) { System.out.println("Fatal I/O Error !"); System.exit(0); } }
S dng hm getInputStream and getOutputStream of class Socket thit lp dng xut/nhp d liu BufferedReader in = new BufferedReader( new InputStreamReader(link.getInputStream())); PrintWriter out = new PrintWriter(link.getOutputStream(),true);
Network Programming
17
Network Programming
18
12/6/2007
V d v my ch TCP Echo(2)
static void handleClient(Socket s) throws IOException { byte[] buff = new byte[BUFSIZE]; int bytesread = 0; // print out client's address System.out.println("Connection from " + s.getInetAddress().getHostAddress()); // Set up streams InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // read/write loop while ((bytesread = in.read(buff)) != -1) { out.write(buff,0,bytesread); } s.close(); } }
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
19
Network Programming
20
Hm khi to DatagramPacket
Vi bn nhn: DatagramPacket(byte[] buf, int len); Vi bn gi: DatagramPacket( byte[] buf, int len InetAddress a, int port);
Cc hm DatagramPacket
byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort();
a ch ch
C th l a ch /c ng ngu n/ch
Network Programming
21
Network Programming
22
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
Network Programming
12/6/2007
2.
public void disconnect( ) public int getPort( ) public InetAddress getInetAddress( ) public InetAddress getRemoteSocketAddress( ) // Java 1.4
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
25
Network Programming
26
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
3.
9.
4.
To i tng kiu DatagramSocket 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];
27
Network Programming
28
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 }
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
29
Network Programming
30
12/6/2007
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 }
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
31
Network Programming
32
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
33