Tài liệu Lập trình mạng P4 doc

33 312 0
Tài liệu Lập trình mạng P4 doc

Đ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 [...]... 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 3 1 Socket trong java Lập trình Socket... 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 java Ví dụ lập trình Socket... client Client – Khởi tạo TCP socket – Xác định IP address, port number của server – Thiết lập kết nối đến server Khi server nhận yêu cầu kết nối, nó sẽ chấp nhận yêu cầu và khởi tạo socket mới để giao tiếp với client – Có thể server chấp nhận nhiều client tại một thời điểm Chương 3 1 Socket trong java Ví dụ lập trình Socket với TCP Server Client (running on hostid) create socket, port=x, for incoming... 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 Ví dụ xây dựng chương trình TCPEcho...Chương 3 1 Socket trong java Ví dụ lập trình Socket với UDP Server (running on hostid) create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client... create socket, 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... connectionSocket 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... InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; 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); DatagramPacket receivePacket = new DatagramPacket(receiveData,... while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new 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()... clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + 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); . 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 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

Ngày đăng: 22/12/2013, 21:17

Từ khóa liên quan

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

Tài liệu liên quan