38
THỰC HÀNH LẬP TRÌNH MẠNG I. Tra cứu địa chỉ Internet (InetAddress) 1. Viết chương trình in địa chỉ của www.oreilly.com 2. Viết chương trình in địa chỉ của 208.201.239.37 3. Viết chương trình in tất cả địa chỉ của www.microsoft.com 4. Viết chương trình in ra địa chỉ của máy cục bộ (localhost) 5. Viết chương trình cho phép nhập địa chỉ từ bàn phím (từ đối dòng lệnh) rồi in ra hostname 6. Viết chương trình nhập vào hostname và cho biết địa chỉ IP của host đó thuộc lớp nào. 7. Viết chương trình kiểm tra phiên bản địa chỉ IP 8. Viết chương trình kiểm tra loại địa chỉ IP (địa chỉ local, loopback, multicast,…) (java từ 1.4 trở lên) 9. Viết chương trình kiểm tra hai hostname có chung địa chỉ IP 10. Viết chương trình dạng nslookup cho phép tra cứu địa chỉ IP của các hostname được nhập từ bàn phím hay từ đối dòng lệnh II. Lớp URL và URLConnection 11. Viết chương trình kiểm tra các protocol có được máy ảo hỗ trợ 12. Viết chương trình phân tích các thông tin trong một url 13. Viết chương trình hiển thị source của một trang web 14. Viết chương trình kiểm tra xem hai tài nguyên xác định bởi hai đối tượng url có giống nhau. 15. Viết chương trình hiển thị source của một trang web dùng URLConnection 16. Viết chương trình in ra một số thông tin HTTP header 17. Viết chương trình in ra toàn bộ thông tin của một HTTP header III. Socket với giao thức TCP

TH LapTrinhMang 2012

Embed Size (px)

Citation preview

Page 1: TH LapTrinhMang 2012

THỰC HÀNH LẬP TRÌNH MẠNG

I. Tra cứu địa chỉ Internet (InetAddress)1. Viết chương trình in địa chỉ của www.oreilly.com2. Viết chương trình in địa chỉ của 208.201.239.373. Viết chương trình in tất cả địa chỉ của www.microsoft.com4. Viết chương trình in ra địa chỉ của máy cục bộ (localhost)5. Viết chương trình cho phép nhập địa chỉ từ bàn phím (từ đối dòng lệnh) rồi in ra

hostname6. Viết chương trình nhập vào hostname và cho biết địa chỉ IP của host đó thuộc lớp

nào.7. Viết chương trình kiểm tra phiên bản địa chỉ IP8. Viết chương trình kiểm tra loại địa chỉ IP (địa chỉ local, loopback, multicast,…) (java

từ 1.4 trở lên)9. Viết chương trình kiểm tra hai hostname có chung địa chỉ IP10. Viết chương trình dạng nslookup cho phép tra cứu địa chỉ IP của các hostname được

nhập từ bàn phím hay từ đối dòng lệnhII. Lớp URL và URLConnection

11. Viết chương trình kiểm tra các protocol có được máy ảo hỗ trợ12. Viết chương trình phân tích các thông tin trong một url13. Viết chương trình hiển thị source của một trang web14. Viết chương trình kiểm tra xem hai tài nguyên xác định bởi hai đối tượng url có giống

nhau.15. Viết chương trình hiển thị source của một trang web dùng URLConnection16. Viết chương trình in ra một số thông tin HTTP header17. Viết chương trình in ra toàn bộ thông tin của một HTTP header

III.Socket với giao thức TCP18. Viết chương trình (client) kiểm tra trong 1024 cổng đầu tiên của một host, cổng nào

đang có tuyến trình server đang lắng nghe. (tương tự kiểm tra trên các cổng từ 1024 - 65535)

19. Viết chương trình in ra thông tin của socket (remote host, remote port, local address, local port)

20. Viết chương trình (server) kiểm tra trong 1024 cổng đầu tiên, cổng nào đang có tuyến trình server lắng nghe.

21. Viết chương trình tạo ra một tuyến trình server lắng nghe trên một cổng ngẫu nhiên22. Viết chương trình client/server (datetime) cho giao thức TCP:

- Client: kết nối tới server, nhận một chuỗi do server gửi về và hiển thị ra màn hình- Server: chấp nhận kết nối từ một client, gửi thông tin ngày, tháng, năm dưới dạng

một chuỗi cho client.23. Viết chương trình client/server (echo) cho giao thức TCP:

Page 2: TH LapTrinhMang 2012

- Client: nhận một dòng văn bản do người dùng nhập vào, gửi văn bản tới server, nhận một chuỗi do server gửi về và hiển thị ra màn hình

- Server: nhận dòng văn bản do client gửi tới, rồi gửi trả lại cho client.IV.Lập trình ứng dụng với giao thức UDP

24. Xây dựng một DatagramPacket để nhận dữ liệu25. Chương trình tìm kiếm các cổng trên máy cục bộ cho tuyến trình server dùng giao

thức UDP26. Xây dưng chương trình client/server tương tự như yêu cầu của câu 24 cho giao thức

UDP.V. Một số các bài tập khác.

27. Viết chương trình theo mô hình Client-Server sử dụng dụng Socket ở chế độ có nối kết. Trong đó : + Server làm nhiệm vụ đọc một ký tự số từ '0' đến '9'. ( Ví dụ : nhận số 0 : trả về

“khong", 1 : trả về "một" ; ... ... 9 : trả về "chín", nếu nhận ký tự khác số thì trả về "Không phải số nguyên" ).

+ Client sẽ nhập vào 1 ký tự, gửi qua Server, nhận kết quả trả về từ Server và thể hiện lên màn hình28. Viết chương trình theo mô hình Client-Server sử dụng Socket ở chế độ có nối kết.

Trong đó : + Server sẽ nhận các yêu cầu là một chuỗi có khuôn dạng như sau: "OP Operant1 Operant2\n" Trong đó: - OP là một ký tự chỉ phép toán muốn thực hiện: '+','-', '*', '/' - Operant1, Operant2 là đối số của phép toán. - Các thành phần trên cách nhau bởi 1 ký tự trắng ' '. - Kết thúc yêu cầu bằng ký tự xuống dòng '\n'.

Mỗi khi server nhận được một thông điệp nó sẽ thực hiện phép toán: Operant1 OP Operant2 để cho ra kết quả, sau đó đổi kết quá thành chuỗi và gởi về Client.

+ Client cho phép người dùng nhập các phép toán muốn tính theo cách thức thông thường. Ví dụ: 100+200. Client tạo ra thông điệp yêu cầu theo đúng dạng do Server qui định, mô tả về phép toán muốn Server thực thi, rồi gởi sang Server, chờ nhận kết quả trả về và in ra màn hình.

VI. Lập trình Multicast29. Xây dựng chương trình Multicast theo yêu cầu sau: Tham gia vào nhóm của

multicast; Gửi dữ liệu đến địa chỉ multicast; nhận dữ liệu từ nhóm multicast và hiển thị lên màn hình.

30. Xây dựng chương trình broadcast theo yêu cầu sau:

Page 3: TH LapTrinhMang 2012

- Server đọc từng dòng dữ liệu từ file văn bản (tạo tùy ý), gửi dữ liệu này đến một địa chỉ multicast 230.2.0.2.- Các client sau khi gia nhập nhóm multicast sẽ nhận được dữ liệu server gửi và hiển thị lên màn hình.

VII. Lập trình RMI31. Sử dụng Java RMI viết chương trình tính giai thừa số nguyên N như sau:

- Chương trình chạy trên máy chủ có phương thức Giaithua là phương thức có thể gọi từ xa. Phương thức này thực hiện việc tính giai thừa của số nguyên N (N được cho dưới dạng tham số của phương thức)- Chương trình Client thực hiện nhận vào từ bàn phím số nguyên N và gọi phương thức Giaithua của server ở xa để tính giai thừa của số nguyên N, rồi in kết quả ra màn hình.Viết các module của chương trình, nêu các bước cài đặt và chạy chương trình trên máy server và client.

32. Sử dụng Java RMI viết chương trình tính phần tử thứ N của dãy Fibonaci như sau:- Chương trình chạy trên máy chủ có phương thức Fibonaci là phương thức có thể gọi từ xa. Phương thức này thực hiện việc tính phần tử thứ N của dãy Fibonaci (N được cho dưới dạng tham số của phương thức)- Chương trình Client thực hiện nhận vào từ bàn phím số nguyên N và gọi phương thức Fibonaci của Server với tham số N. Kết quả được in ra màn hình cửa sổ lệnh.Viết các module của chương trình, nêu các bước cài đặt và chạy chương trình trên máy server và client.Viết các module của chương trình, nêu các bước cài đặt và chạy chương trình trên máy server và client.

Page 4: TH LapTrinhMang 2012

--------------------------------------------------------------------------------

Mã nguồn (Java network programming)I.1.

import java.net.*;public class OReillyByName { public static void main (String[] args) { try { InetAddress address = InetAddress.getByName("www.oreilly.com"); System.out.println(address); } catch (UnknownHostException ex) { System.out.println("Could not find www.oreilly.com"); } }

}2.

import java.net.*;public class OReillyByAddress { public static void main (String[] args) { try { InetAddress address = InetAddress.getByName("208.201.239.37"); System.out.println(address); } catch (UnknownHostException ex) { System.out.println("Could not find 208.201.239.37"); } }

}3.

import java.net.*;public class AllAddressesOfMicrosoft { public static void main (String[] args) { try { InetAddress[] addresses = InetAddress.getAllByName("www.microsoft.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } }

Page 5: TH LapTrinhMang 2012

catch (UnknownHostException ex) { System.out.println("Could not find www.microsoft.com"); } }

}4.

import java.net.*;public class MyAddress { public static void main(String[] args) { try { InetAddress me = InetAddress.getLocalHost(); String dottedQuad = me.getHostAddress(); System.out.println("My address is " + dottedQuad); } catch (UnknownHostException ex) { System.out.println("I'm sorry. I don't know my own address."); } }

}5. 6. 7.

import java.net.*;public class AddressTests { public static int getVersion(InetAddress ia) { byte[] address = ia.getAddress( ); if (address.length == 4) return 4; else if (address.length == 16) return 6; else return -1; }}8.

import java.net.*;public class IPCharacteristics { public static void main(String[] args) { try { InetAddress address = InetAddress.getByName(args[0]); if (address.isAnyLocalAddress()) { System.out.println(address + " is a wildcard address."); } if (address.isLoopbackAddress()) {

Page 6: TH LapTrinhMang 2012

System.out.println(address + " is loopback address."); } if (address.isLinkLocalAddress()) { System.out.println(address + " is a link-local address."); } else if (address.isSiteLocalAddress()) { System.out.println(address + " is a site-local address."); } else { System.out.println(address + " is a global address."); } if (address.isMulticastAddress()) { if (address.isMCGlobal()) { System.out.println(address + " is a global multicast address."); } else if (address.isMCOrgLocal()) { System.out.println(address + " is an organization wide multicast address."); } else if (address.isMCSiteLocal()) { System.out.println(address + " is a site wide multicast address."); } else if (address.isMCLinkLocal()) { System.out.println(address + " is a subnet wide multicast address."); } else if (address.isMCNodeLocal()) { System.out.println(address + " is an interface-local multicast address."); } else { System.out.println(address + " is an unknown multicast address type."); } } else { System.out.println(address + " is a unicast address."); } } catch (UnknownHostException ex) { System.err.println("Could not resolve " + args[0]); } }

Page 7: TH LapTrinhMang 2012

}9.

import java.net.*;public class IBiblioAliases { public static void main (String args[]) { try { InetAddress ibiblio = InetAddress.getByName("www.ibiblio.org"); InetAddress helios = InetAddress.getByName("helios.metalab.unc.edu"); if (ibiblio.equals(helios)) { System.out.println ("www.ibiblio.org is the same as helios.metalab.unc.edu"); } else { System.out.println ("www.ibiblio.org is not the same as helios.metalab.unc.edu"); } } catch (UnknownHostException ex) { System.out.println("Host lookup failed."); } }

}10.

import java.net.*;import java.io.*;public class HostLookup { public static void main (String[] args) { if (args.length > 0) { // use command line for (int i = 0; i < args.length; i++) { System.out.println(lookup(args[i])); } } else { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter names and IP addresses. Enter \"exit\" to quit."); try { while (true) { String host = in.readLine(); if (host.equalsIgnoreCase("exit") || host.equalsIgnoreCase("quit")) { break; }

Page 8: TH LapTrinhMang 2012

System.out.println(lookup(host)); } } catch (IOException ex) { System.err.println(ex); }

} } /* end main */

private static String lookup(String host) { InetAddress node; // get the bytes of the IP address try { node = InetAddress.getByName(host); } catch (UnknownHostException ex) { return "Cannot find host " + host; } if (isHostname(host)) { return node.getHostAddress(); } else { // this is an IP address return node.getHostName(); } } // end lookup

private static boolean isHostname(String host) {

// Is this an IPv6 address? if (host.indexOf(':') != -1) return false;

char[] ca = host.toCharArray(); // if we see a character that is neither a digit nor a period // then host is probably a hostname for (int i = 0; i < ca.length; i++) { if (!Character.isDigit(ca[i])) { if (ca[i] != '.') return true; } }

Page 9: TH LapTrinhMang 2012

// Everything was either a digit or a period // so host looks like an IPv4 address in dotted quad format return false; } // end isHostName

} // end HostLookupII.11.

/* Which protocols does a virtual machine support? */import java.net.*;

public class ProtocolTester { public static void main(String[] args) {

// hypertext transfer protocol testProtocol("http://www.adc.org");

// secure http testProtocol("https://www.amazon.com/exec/obidos/order2/");

// file transfer protocol testProtocol("ftp://metalab.unc.edu/pub/languages/java/javafaq/");

// Simple Mail Transfer Protocol testProtocol("mailto:[email protected]");

// telnet testProtocol("telnet://dibner.poly.edu/");

// local file access testProtocol("file:///etc/passwd");

// gopher testProtocol("gopher://gopher.anc.org.za/");

// Lightweight Directory Access Protocol testProtocol( "ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US?postalAddress");

// JAR testProtocol( "jar:http://cafeaulait.org/books/javaio/ioexamples/javaio.jar!"

Page 10: TH LapTrinhMang 2012

+"/com/macfaq/io/StreamCopier.class");

// NFS, Network File System testProtocol("nfs://utopia.poly.edu/usr/tmp/");

// a custom protocol for JDBC testProtocol("jdbc:mysql://luna.metalab.unc.edu:3306/NEWS");

// rmi, a custom protocol for remote method invocation testProtocol("rmi://metalab.unc.edu/RenderEngine");

// custom protocols for HotJava testProtocol("doc:/UsersGuide/release.html"); testProtocol("netdoc:/UsersGuide/release.html"); testProtocol("systemresource://www.adc.org/+/index.html"); testProtocol("verbatim:http://www.adc.org/"); }

private static void testProtocol(String url) { try { URL u = new URL(url); System.out.println(u.getProtocol() + " is supported"); } catch (MalformedURLException ex) { String protocol = url.substring(0, url.indexOf(':')); System.out.println(protocol + " is not supported"); } }

}12.

import java.net.*;

public class URLSplitter { public static void main(String args[]) { for (int i = 0; i < args.length; i++) { try { URL u = new URL(args[i]); System.out.println("The URL is " + u); System.out.println("The scheme is " + u.getProtocol()); System.out.println("The user info is " + u.getUserInfo());

Page 11: TH LapTrinhMang 2012

String host = u.getHost(); if (host != null) { int atSign = host.indexOf('@'); if (atSign != -1) host = host.substring(atSign+1); System.out.println("The host is " + host); } else { System.out.println("The host is null."); } System.out.println("The port is " + u.getPort()); System.out.println("The path is " + u.getPath()); System.out.println("The ref is " + u.getRef()); System.out.println("The query string is " + u.getQuery()); } // end try catch (MalformedURLException ex) { System.err.println(args[i] + " is not a URL I understand."); } System.out.println(); } // end for } // end main

} // end URLSplitter13.

import java.net.*;import java.io.*;

public class SourceViewer { public static void main (String[] args) { if (args.length > 0) { try { //Open the URL for reading URL u = new URL(args[0]); InputStream in = u.openStream(); // buffer the input to increase performance in = new BufferedInputStream(in); // chain the InputStream to a Reader Reader r = new InputStreamReader(in); int c; while ((c = r.read()) != -1) { System.out.print((char) c); } }

Page 12: TH LapTrinhMang 2012

catch (MalformedURLException ex) { System.err.println(args[0] + " is not a parseable URL"); } catch (IOException ex) { System.err.println(ex); } } // end if } // end main

} // end SourceViewer14.

import java.net.*;

public class URLEquality { public static void main (String[] args) { try { URL ibiblio = new URL ("http://www.ibiblio.org/"); URL metalab = new URL("http://metalab.unc.edu/"); if (ibiblio.equals(metalab)) { System.out.println(ibiblio + " is the same as " + metalab); } else { System.out.println(ibiblio + " is not the same as " + metalab); } } catch (MalformedURLException ex) { System.err.println(ex); } }

}15.

import java.net.*;import java.io.*;

public class SourceViewer2 { public static void main (String[] args) { if (args.length > 0) { try { //Open the URLConnection for reading URL u = new URL(args[0]); URLConnection uc = u.openConnection(); InputStream raw = uc.getInputStream();

Page 13: TH LapTrinhMang 2012

InputStream buffer = new BufferedInputStream(raw); // chain the InputStream to a Reader Reader r = new InputStreamReader(buffer); int c; while ((c = r.read()) != -1) { System.out.print((char) c); } } catch (MalformedURLException ex) { System.err.println(args[0] + " is not a parseable URL"); } catch (IOException ex) { System.err.println(ex); } } // end if } // end main

} // end SourceViewer216.

import java.net.*;import java.io.*;import java.util.*;

public class HeaderViewer { public static void main(String args[]) { for (int i=0; i < args.length; i++) { try { URL u = new URL(args[0]); URLConnection uc = u.openConnection(); System.out.println("Content-type: " + uc.getContentType()); System.out.println("Content-encoding: " + uc.getContentEncoding()); System.out.println("Date: " + new Date(uc.getDate())); System.out.println("Last modified: " + new Date(uc.getLastModified())); System.out.println("Expiration date: " + new Date(uc.getExpiration())); System.out.println("Content-length: " + uc.getContentLength()); } // end try catch (MalformedURLException ex) { System.err.println(args[i] + " is not a URL I understand"); }

Page 14: TH LapTrinhMang 2012

catch (IOException ex) { System.err.println(ex); } System.out.println(); } // end for } // end main

} // end HeaderViewer17.

import java.net.*;import java.io.*;

public class AllHeaders { public static void main(String args[]) { for (int i=0; i < args.length; i++) { try { URL u = new URL(args[i]); URLConnection uc = u.openConnection(); for (int j = 1; ; j++) { String header = uc.getHeaderField(j); if (header == null) break; System.out.println(uc.getHeaderFieldKey(j) + ": " + header); } // end for } // end try catch (MalformedURLException ex) { System.err.println(args[i] + " is not a URL I understand."); } catch (IOException ex) { System.err.println(ex); } System.out.println(); } // end for } // end main

} // end AllHeadersIII.18.

import java.net.*;import java.io.*;

public class LowPortScanner { public static void main(String[] args) { String host = "localhost";

Page 15: TH LapTrinhMang 2012

if (args.length > 0) { host = args[0]; } for (int i = 1; i < 1024; i++) { try { Socket s = new Socket(host, i); System.out.println("There is a server on port " + i + " of " + host); } catch (UnknownHostException ex) { System.err.println(ex); break; } catch (IOException ex) { // must not be a server on this port } } // end for

} // end main

} // end PortScanner19.

import java.net.*;import java.io.*;

public class SocketInfo {

public static void main(String[] args) {

for (int i = 0; i < args.length; i++) { try { Socket theSocket = new Socket(args[i], 80); System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort() + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress()); } // end try catch (UnknownHostException ex) { System.err.println("I can't find " + args[i]); }

Page 16: TH LapTrinhMang 2012

catch (SocketException ex) { System.err.println("Could not connect to " + args[i]); } catch (IOException ex) { System.err.println(ex); }

} // end for

} // end main

} // end SocketInfo

20. import java.net.*;import java.io.*;

public class LocalPortScanner { public static void main(String[] args) {

for (int port = 1; port <= 1024; port++) {

try { // the next line will fail and drop into the catch block if // there is already a server running on the port ServerSocket server = new ServerSocket(port); } catch (IOException ex) { System.out.println("There is a server on port " + port + "."); } // end catch

} // end for }

}21.

import java.net.*;import java.io.*;

public class RandomPort {

public static void main(String[] args) {

Page 17: TH LapTrinhMang 2012

try { ServerSocket server = new ServerSocket(0); System.out.println("This server runs on port " + server.getLocalPort()); } catch (IOException ex) { System.err.println(ex); }

}

}22.Chương trình phía server

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 }

}

try {

Page 18: TH LapTrinhMang 2012

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 DaytimeServerChương trình phía client

import java.net.*;import java.io.*;

public class DaytimeClient {

public static void main(String[] args) {

String hostname;

Page 19: TH LapTrinhMang 2012

if (args.length > 0) { hostname = args[0]; } else { hostname = "localhost"; }

try { Socket theSocket = new Socket(hostname, 13); 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 e) { System.err.println(e); } catch (IOException e) { System.err.println(e); }

} // end main

} // end DaytimeClient23.

Chương trình phía client

import java.net.*;

import java.io.*;

public class EchoClient1

{

public static void main(String[] args)

{

String hostname="localhost";

if(args.length>0)

{

Page 20: TH LapTrinhMang 2012

hostname=args[0];

}

PrintWriter pw=null;

BufferedReader br=null;

try{

Socket s=new Socket(hostname,2007);

br=new BufferedReader(new InputStreamReader(s.getInputStream()));

BufferedReader user=new BufferedReader(new InputStreamReader(System.in));

pw=new PrintWriter(s.getOutputStream());

System.out.println("Da ket noi duoc voi server...");

while(true)

{

String st=user.readLine();

if(st.equals("exit"))

{

break;

}

pw.println(st);

pw.flush();

System.out.println(br.readLine());

}

}

catch(IOException e)

{

System.err.println(e);

}

finally{

try{

if(br!=null)br.close();

if(pw!=null)pw.close();

}

catch(IOException e)

Page 21: TH LapTrinhMang 2012

{

System.err.println(e);

}

}

}

}

Chương trình phía server

import java.net.*;

import java.io.*;

public class EchoServer1

{

public final static int DEFAULT_PORT=2007;

public static void main(String[] args)

{ int port=DEFAULT_PORT;

try{

ServerSocket ss=new ServerSocket(port);

Socket s=null;

while(true)

{

try{

s=ss.accept();

PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));

while(true){

String line=br.readLine();

if(line.equals("exit"))break;

String upper=line.toUpperCase();

pw.println(upper);

Page 22: TH LapTrinhMang 2012

pw.flush();

}

}

catch(IOException e)

{

}

finally{

try{

if(s!=null){

s.close();

}

}

catch(IOException e){}

}

}

}

catch(IOException e)

{

}

}

}

IV

24.

import java.net.*;

public class DatagramExample {

public static void main(String[] args) {

String s = "This is a test.";

byte[] data = s.getBytes();

try {

InetAddress ia = InetAddress.getByName("www.ibiblio.org");

int port = 7;

Page 23: TH LapTrinhMang 2012

DatagramPacket dp

= new DatagramPacket(data, data.length, ia, port);

System.out.println("This packet is addressed to "

+ dp.getAddress() + " on port " + dp.getPort());

System.out.println("There are " + dp.getLength()

+ " bytes of data in the packet");

System.out.println(

new String(dp.getData(), dp.getOffset(), dp.getLength()));

}

catch (UnknownHostException e) {

System.err.println(e);

}

}

}

25.import java.net.*;

public class UDPPortScanner { public static void main(String[] args) {

for (int port = 1024; port <= 65535; port++) { try { // the next line will fail and drop into the catch block if // there is already a server running on port i DatagramSocket server = new DatagramSocket(port); server.close(); } catch (SocketException ex) { System.out.println("There is a server on port " + port + "."); } // end try } // end for }

}26.

Chương trình phía client

import java.net.*;

Page 24: TH LapTrinhMang 2012

import java.io.*;

public class UDPClient {

public final static int CONG_MAC_DINH=9;

public static void main(String args[])

{

String hostname;

int port=CONG_MAC_DINH;

if(args.length>0)

{

hostname=args[0];

try{

}

catch(Exception e){

port =Integer.parseInt(args[1]);

}

}

else

{

hostname="127.0.0.1";

}

try{

InetAddress dc=InetAddress.getByName(hostname);

BufferedReader userInput=new BufferedReader(new InputStreamReader(System.in));

DatagramSocket ds =new DatagramSocket(port);

while(true){

String line=userInput.readLine();

if(line.equals("exit"))break;

byte[] data=line.getBytes();

DatagramPacket dp=new DatagramPacket(data,data.length,dc,port);

ds.send(dp);

dp.setLength(65507);

Page 25: TH LapTrinhMang 2012

ds.receive(dp);

ByteArrayInputStream bis =new ByteArrayInputStream(dp.getData());

BufferedReader dis =new BufferedReader(new InputStreamReader(bis));

System.out.println(dis.readLine());

}

}

catch(UnknownHostException e)

{

System.err.println(e);

}

catch(IOException e)

{

System.err.println(e);

}

}

}

Chương trình phía server

import java.net.*;

import java.io.*;

public class UDPServer

{

public final static int CONG_MAC_DINH=9;

public static void main(String args[])

{

int port=CONG_MAC_DINH;

Page 26: TH LapTrinhMang 2012

try{

}

catch(Exception e){

port =Integer.parseInt(args[1]);

}

try{

DatagramSocket ds =new DatagramSocket(port);

DatagramPacket dp=new DatagramPacket(new byte[65507],65507);

while(true){

ds.receive(dp);

ByteArrayInputStream bis =new ByteArrayInputStream(dp.getData());

BufferedReader dis =new BufferedReader(new InputStreamReader(bis));

String s=dis.readLine();

System.out.println(s);

s.toUpperCase();

dp.setData(s.getBytes());

dp.setLength(s.length());

dp.setAddress(dp.getAddress());

dp.setPort(dp.getPort());

ds.send(dp);

}

}

catch(UnknownHostException e)

{

System.err.println(e);

}

Page 27: TH LapTrinhMang 2012

catch(IOException e)

{

System.err.println(e);

}

}

}

27>

Sẻverimport java.io.BufferedReader;

import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;

/**** @author VanDuc*/public class Server {

/*** @param args the command line arguments*/private static ServerSocket serverSocket = null;public static void main(String[] args) throws IOException{// TODO code application logic here

PrintWriter out = null;DataOutputStream dos = null; DataInputStream dis=null;try {serverSocket = new ServerSocket(1027);System.out.print("Server đã được mở \n" );Socket clientSocket = null;clientSocket = serverSocket.accept();dos=new DataOutputStream(clientSocket.getOutputStream());dis=new DataInputStream(clientSocket.getInputStream());String inline="";while(true) { inline = dis.readUTF();char ch[]=inline.toCharArray();if(Character.isDigit(ch[0])){int i=Integer.parseInt(inline);switch(i){case 0:inline="Không";break;case 1:inline="Một";break;case 2:inline="Hai";break;case 3:inline="Ba";break;

Page 28: TH LapTrinhMang 2012

case 4:inline="Bốn";break;case 5:inline="Năm";break;case 6:inline="Sáu";break;case 7:inline="Bảy";break;case 8:inline="Tám";break;case 9:inline="Chín";break;}dos.writeUTF(inline);}elsedos.writeUTF("Không phải số nguyên");}}catch(Exception e) {        dos.close();    serverSocket.close();    dis.close();System.out.print(e.getMessage());}}}  

phia client:

import java.io.BufferedReader;

import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.util.Scanner;

/**** @author VanDuc*/public class Client{

/*** @param args the command line arguments*/public static void main(String[] args) throws IOException{// TODO code application logic here

Socket mySocket = null;DataOutputStream dos = null; DataInputStream dis=null;

try {mySocket = new Socket("localhost", 1027);dos = new DataOutputStream(mySocket.getOutputStream());dis = new DataInputStream(mySocket.getInputStream());Scanner input = new Scanner(System.in);String s = null;while(true){System.out.print("\nNhap du lieu: ");

Page 29: TH LapTrinhMang 2012

s =input.nextLine();dos.writeUTF(s);String str=dis.readUTF();System.out.print("Kết quả từ Server : "+str);} }catch(Exception e) {    System.out.print("Ngat ket noi");    dis.close();    dos.close();    mySocket.close();e.printStackTrace();}}}

29

Server

import java.net.DatagramPacket;import java.net.InetAddress;import java.net.MulticastSocket;import java.util.Scanner;

public class Server {    MulticastSocket multiSocket;    InetAddress ip;    public void runServer() {        try {            multiSocket = new MulticastSocket(8080);            InetAddress ip = InetAddress.getByName("225.225.225.225");            multiSocket.joinGroup(ip);            DataStream das=new DataStream(this);            byte[] send;            Scanner input = new Scanner(System.in);            while (true) {                System.out.println("Nhap chuoi : ");                send = new byte[256];                send = input.nextLine().getBytes();                DatagramPacket sendPacket = new DatagramPacket(send,                        send.length, ip, 8080);                multiSocket.send(sendPacket);            }        } catch (Exception e) {            // TODO: handle exception        }    }

    public static void main(String[] args) {        new Server().runServer();    }}

phía client