Professional Documents
Culture Documents
Lap Trinh Socket Java 4534
Lap Trinh Socket Java 4534
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 chu i k t nh p 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. Thi t l p k t n i 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
L p java.net.ServerSocket bao g m
Cc hm kh i t o i t ng ServerSocket Cc hm ch k t n i Cc hm thi t l p cc lo i ty ch n socket my ch Cc hm th ng dng khc nh toString( )
C b n hm kh i t o ServerSocket cho php thi t l p c ng, kch th c hng i c a cc yu c u k t n i v network interface gn cho ti n 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. T om t
2.
i t ng ServerSocket
3. 4.
5.
a my ch vo tr ng thi ch Socket link = servSocket.accept(); Thi t l p cc dng xu t/nh p d li u G i v nh n d li u out.println(awaiting data); String input = in.readLine(); ng k t n i 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 d ng hm getInputStream and getOutputStream of class Socket thi t l p dng xu t/nh p d li u 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
Bi u di n cc gi d li u UDP Cung c p cc hm
L y v thi t l p a ch ch/ngu n t /vo tiu L y v thi t l p c ng giao ti p ch/ngu n Nh n v thi t l p gi d li u UDP IP
Network Programming
19
Network Programming
20
Hm khi to DatagramPacket
V i bn nh n: DatagramPacket(byte[] buf, int len); V i bn g i: 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
T o datagram socket nh n DatagramPacket.
Khng c phn bi t gi a socket my khch v socket my ch M t DatagramSocket c th g i cho nhi u a ch ch khc nhau.
a ch ch c lu t i DatagramPacket
public DatagramSocket() throws SocketException public DatagramSocket(int port) throws SocketException public DatagramSocket(int port, InetAddress laddr) throws SocketException
Network Programming
a ch IP m socket ang s d ng
24
Network Programming
12/6/2007
2.
public void disconnect( ) public int getPort( ) public InetAddress getInetAddress( ) public InetAddress getRemoteSocketAddress( ) // Java 1.4
3.
4.
Kh i t o m t i t ng ki u DatagramSocket DatagramSocket dgramSocket = new DatagramSocket(1234); T o buffer cho dng d li u nh p byte[] buffer = new byte[256]; T o i t ng ki u DatagramPacket cho dng d li u nh p DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length); Ch dng d li u nh p dgramSocket.receive(inPacket)
Network Programming
25
Network Programming
26
6.
7.
L y a ch v c ng c a bn g i t gi tin nh n c InetAddress clientAddress = inPacket.getAddress(); int clientPort = inPacket.getPort(); L y d li u t buffer string message = new String(inPacket.getData(), 0, inPacket.getLength()); T o gi d li u UDP xu t
3.
9.
4.
T o i t ng ki u DatagramSocket DatagramSocket dgramSocket = new DatagramSocket; T o gi d li u UDP xu t DatagramPacket outPacket = new DatagramPacket( message.getBytes(), message.length(), host, port); G i gi d li u dgramSocket.send(outPacket) T o buffer cho d li u nh p 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.
T o i t ng ki u DatagramPacket cho gi d li u nh p DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length); Nh n gi d li u nh p dgramSocket.receive(inPacket) L y d li u 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