You are on page 1of 6

12/6/2007

Ni dung bi hc

Lp trnh Socket vi Java

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

Network Programming

Cc classes trong gi java.net


Gi java.net cha cc classes cho php thc hin lp trnh mng
ContentHandler DatagramPacket DatagramSocket InetAddress MulticastSocket ServerSocket Socket SocketImpl URL URLConnection URLEncoder URLStreamHandler

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); } } }

X l a ch Internet theo tn v a ch IP Cc hm chuyn i tn/a ch: /* tr v mt i tng kiu InetAddress*/

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!"); } } }

Truyn tin vi giao thc TCP


TCP server TCP client
ServerSocket () socket() ServerSocket. accept()

connect()

Connection request data (request)

write()

BufferedReader. readLine() Process request PrintWriter. println() BufferedReader. readLine() ServerSocket. close()

Wait next request

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

The Java.net.Socket Class (2)


Gi v nhn d liu c thc hin thng qua dng d liu xut/nhp
C mt s hm ly i tng l dng nhp cho mt socket v dng xut cho socket . public InputStream getInputStream() throws IOException public OutputStream getOutputStream() throws IOException public InetAddress getInetAddress( ) public int getPort( ) public int getLocalPort( ) public InetAddress getLocalAddress( ) 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

Ly thng tin v mt Socket

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; }

Thit lp cc dng xut/nhp d liu Gi v nhn d liu ng kt ni

Network Programming

11

Network Programming

12

12/6/2007

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

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

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 Socket

TCP Sockets
MY CH: 1. To mt i tng ServerSocket
ServerSocket servSocket = new ServerSocket(1234);
2.

3. 4.

public void close() throws IOException


ng socket my ch v gii phng cng ch

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

Thit lp dng xut/nhp d liu


Khi mt socket c kt ni
chng ta c th gi d liu thng qua mt dng xut d liu chng ta c th nhn d liu thng qua mt dng nhp d liu

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

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


Nhn gi d liu UDP v lu li ti i tng kiu DatagramPacket c to ra t trc

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

public void close( )


Gii phng cng ang oc s dng bi socket

public int getLocalPort( )


Tr v s hiu cng m socket ang s dng

public InetAddress getLocalAddress( )


Tr v a ch IP m socket ang s dng
23 24

Network Programming

12/6/2007

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

Cc bc thit lp truyn tin UDP - MY CH


1.

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

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

Cc bc thit lp truyn tin UDP My khch (1)


1. 2.

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


8.

3.

9.

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


Network Programming

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

Cc bc thit lp truyn tin UDP My khch (2)


5.

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

You might also like