Lập trình mạng trong Java - Chương 4 pps

33 497 2
Lập trình mạng trong Java - Chương 4 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chương 4: Lậptrìnhmạng trong Java Chương 3 1. Socket trong java Java hỗ trợ lập trình mạng thông qua các lớp trong gói java.net. Mộtsố gói tiêu biểu - InetAddress: Quảnlýđịachỉ internet bao gồm địachỉ IP và tên máy - Socket: hỗ trợ phương thức liên quan tới socket cho chương trình client ở chếđộcó kếtnối - ServerSocket: hỗ trợ phương thức liên quan tới socket cho chương trình Server ở chếđộcó kếtnối - DatagramSocket: hỗ trợ các phương thức liên quan tới socket ở cả client và server ở chế độ không kết nối - DatagramPacket: cài đặt gói tin dạng thư tín người dùng trong giao tiếp client server ở chế độ không kết nối - URL - URLConnection Chương 3 1. Socket trong java Lớp InetAddress Class mô tả vềđịachỉ IP (Internet Protocol) –Cácphương thức getLocalHost, getByName, hay getAllByName để tạomột InetAddress instance: • public static InetAddess InetAddress.getByName(String hostname) • public static InetAddess [] InetAddress.getAllByName(String hostname) • public static InetAddess InetAddress.getLocalHost() – Để lấy địachỉ IP hay tên dùng các phương thức: • getHostAddress() • getHostName() Chương 3 1. Socket trong java Lớp InetAddress Ví dụ: In địachỉ IP của localhost import java.net.*; public class HostInfo { public static void main(String args[]) { HostInfo host = new HostInfo(); host.init(); } public void init() { try { InetAddress myHost = InetAddress.getLocalHost(); System.out.println(myHost.getHostAddress()); System.out.println(myHost.getHostName()); } catch (UnknownHostException ex) { System.err.println("Cannot find local host"); } } } Chương 3 1. Socket trong java Lớp InetAddress Ví dụ: In địachỉ IP của yahoo.com import java.net.*; class indiachi{ public static void main (String args[]) { try { InetAddress[] addresses = InetAddress.getAllByName(“yahoo.com"); for (int i = 0; i < addresses.length; i++) { System.out.println(addresses[i]); } } catch (UnknownHostException e) { System.out.println("Could not find yahoo.com"); } } } Chương 3 1. Socket trong java Lớp Socket Class mô tả về socket –Tạomột socket • Socket(InetAddress address, int port) • Socket(String host, int port) • Socket(InetAddress address, int port, InetAddress, localAddr, int localPort) • Socket(String host, int port, InetAddress, localAddr, int localPort) • Socket() –Lấy thông tin về một socket • InetAddress getInetAddress() : trả vềđịachỉ mà socket kếtnối đến. • int getPort() : trả về port mà socket kếtnối đến. • InetAddress getLocalAddress() : trả vềđịachỉ cụcbộ. • int getLocalPort() : trả về port cụcbộ. Chương 3 1. Socket trong java Lớp Socket -Sử dụng Streams • public OutputStream getOutputStream() throws IOException Trả về một output stream cho việcviết các byte đến socket này. • public InputStream getInputStream() throws IOException Trả về một input stream cho việc đọc các byte từ socket này. Chương 3 Lớp Socket, ví dụ kết nối tới một server import java.net.*; import java.io.*; public class getSocketInfo { 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()); } catch (UnknownHostException e) { System.err.println("I can't find " + args[i]); } catch (SocketException e) { System.err.println("Could not connect to " + args[i]); } catch (IOException e) { System.err.println(e); } } // end for } // end main } // end getSocketInfo 1. Socket trong java Chương 3 Lớp ServerSocket – Class mô tả về ServerSocket –Tạomột ServerSocket • ServerSocket(int port) throws IOException • ServerSocket(int port, int backlog) throws IOException • ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException –Cácphương thức trong ServerSocket • Socket accept() throws IOException : Lắng nghe mộtkếtnối đến socket này và chấpnhậnnó. • void close() throws IOException : Đóng socket. • InetAddress getInetAddress() : trả vềđịachỉ cụcbộ của socket • int getLocalPort() : Trả về port mà server đang lắng nghe. • void setSoTimeout(int timeout) throws SocketException 1. Socket trong java Chương 3 Lập trình Socket với UDP 9 Cung cấpcơ chế truyền không tin cậygiữa các nhóm các byte (datagrams) giữa client và server. 9 Không cầnthiếtlậpkếtnốigiữa client và server. 9 Sender phảigởikèmđịachỉ IP và port đích 9 Server khi nhậndữ liệusẽ phân tích địachỉ của sender để truyềnlại. 9 Có thể server chấpnhậnnhiều client tạimộtthời điểm. 1. Socket trong java [...]... + modifiedSentence); clientSocket.close(); } Chương 3 1 Socket trong java Ví dụ lập trình Socket với UDP UDPServer .java import java. io.*; import java. net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[10 24] ; byte[] sendData = new byte[10 24] ; while(true) { DatagramPacket receivePacket... new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[10 24] ; byte[] receiveData = new byte[10 24] ; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Chương 3 1 Socket trong java Ví dụ lập trình Socket với UDP UDPClient .java DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket);... clientSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read reply from clientSocket close clientSocket Chương 3 1 Socket trong java Ví dụ lập trình Socket với UDP UDPClient .java import java. io.*; import java. net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));... setup create socket, connect to hostid, port=x clientSocket = Socket() send request using clientSocket read reply from clientSocket close clientSocket Chương 3 1 Socket trong java Ví dụ lập trình Socket với TCP TCPClient .java import java. io.*; import java. net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser... DataOutputStream(clientSocket.getOutputStream()); Chương 3 1 Socket trong java Ví dụ lập trình Socket với TCP TCPClient .java BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Chương 3 1 Socket trong. .. InputStreamReader(connectionSocket.getInputStream())); Chương 3 1 Socket trong java Ví dụ lập trình Socket với TCP TCPServer .java DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } } Chương 3 2 Ví dụ xây dựng ứng dụng WebServer - Chỉ xử lý một yêu... is = s.getInputStream(); int ch=0; Chương 3 3 Ví dụ xây dựng chương trình TCPEcho STCPEchoServer .java while(true) { ch = is.read(); if(ch == -1 ) break; os.write(ch); } s.close(); } catch (IOException e) { System.err.println(" Connection Error: "+e); } } } catch (IOException e) { System.err.println(" Server Creation Error:"+e); } } } Chương 3 3 Ví dụ xây dựng chương trình TCPEcho PTCPEchoServer cài... Message"); } } Chương 3 3 Ví dụ xây dựng chương trình TCPEcho Trong Unix, dịch vụ Echo được thiết kế theo mô hình Client –server, sử dụng socket làm phương tiện giao tiếp Cổng mặc định là 7 ở hai chế độ kết nối và không kết nối Chương trình TCPEchoClient sẽ kế nối tới EchoServer ở chế độ có kết nối và lần lượt gửi tới các ký tự từ ‘0’ tới ‘9’, chờ nhận kết quả và hiển thị chúng lên màn hình Chương 3 3... String(receivePacket.getData()); Chương 3 1 Socket trong java Ví dụ lập trình Socket với UDP UDPServer .java InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Chương. .. cho client } catch (IOException e) { System.out.println("Connection Error: "+e); Chương 3 3 Ví dụ xây dựng chương trình TCPEcho PTCPEchoServer cài đặt ở chế độ đồng thời, có kết nối PTCPEchoServer .java } } } catch (IOException e) { System.err.println("Create Socket Error: "+e); } } } Chương 3 3 Ví dụ xây dựng chương trình TCPEcho class RequestProcessing extends Thread { Socket channel; //Khai bao . Chương 4: Lậptrìnhmạng trong Java Chương 3 1. Socket trong java Java hỗ trợ lập trình mạng thông qua các lớp trong gói java. net. Mộtsố gói tiêu biểu - InetAddress: Quảnlýđịachỉ. byte[10 24] ; byte[] receiveData = new byte[10 24] ; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Chương 3 1. Socket trong java Ví dụ lập trình Socket với UDP UDPClient .java DatagramPacket. modifiedSentence); clientSocket.close(); } Chương 3 1. Socket trong java Ví dụ lập trình Socket với UDP UDPServer .java import java. io.*; import java. net.*; class UDPServer { public static

Ngày đăng: 30/07/2014, 04:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan