lập trình mạng nguyễn cao đạt chương 4 lập trình mạng trong java sinhvienzone com

33 76 0
lập trình mạng nguyễn cao đạt chương 4 lập trình mạng trong java sinhvienzone com

Đ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

Si nh Vi en Zo ne C om Chương 4: Lập trình mạng Java SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Java hỗ trợ lập trình mạng thơng qua lớp gói java.net Một số gói tiêu C biểu InetAddress: Quản lý địa internet bao gồm địa IP 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ết nối ServerSocket: hỗ trợ phương thức liên quan tới socket cho chương trình nh Vi en - Zo ne - Server chế độ có kết nối - DatagramSocket: hỗ trợ phương thức liên quan tới socket client - Si server chế độ không kết nối DatagramPacket: cài đặt gói tin dạng thư tín người dùng giao tiếp client server chế độ không kết nối - URL - URLConnection SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp InetAddress C Class mô tả địa IP (Internet Protocol) ne – Các phương thức getLocalHost, getByName, hay getAllByName để tạo InetAddress instance: public static InetAddess InetAddress.getByName(String hostname) • public static InetAddess [] InetAddress.getAllByName(String nh Vi en Zo • hostname) • public static InetAddess InetAddress.getLocalHost() – Để lấy địa IP hay tên dùng phương thức: getHostAddress() • getHostName() Si • SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp InetAddress Si nh Vi en Zo ne C Ví dụ: In địa IP 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"); } } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp InetAddress Si nh Vi en Zo ne C Ví dụ: In địa IP 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"); } } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp Socket nh Vi en Zo ne C Class mơ tả socket – Tạo 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ề socket InetAddress getInetAddress() : trả địa mà socket kết nối đến int getPort() : trả port mà socket kết nối đến InetAddress getLocalAddress() : trả địa cục int getLocalPort() : trả port cục Si • • • • SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp Socket public OutputStream getOutputStream() throws IOException ne • C - Sử dụng Streams • Zo Trả output stream cho việc viết byte đến socket public InputStream getInputStream() throws IOException Si nh Vi en Trả input stream cho việc đọc byte từ socket SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Lớp Socket, ví dụ kết nối tới server Si nh Vi en Zo ne C 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 SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java Si nh Vi en Zo ne C om Lớp ServerSocket – Class mô tả ServerSocket – Tạo ServerSocket • ServerSocket(int port) throws IOException • ServerSocket(int port, int backlog) throws IOException • ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException – Các phương thức ServerSocket • Socket accept() throws IOException : Lắng nghe kết nối đến socket chấp nhận • void close() throws IOException : Đóng socket • InetAddress getInetAddress() : trả địa cục socket • int getLocalPort() : Trả port mà server lắng nghe • void setSoTimeout(int timeout) throws SocketException SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java Si nh Vi en Zo ne C om Lập trình Socket với UDP Cung cấp chế truyền khơng tin cậy nhóm byte (datagrams) client server Không cần thiết lập kết nối client server Sender phải gởi kèm địa IP port đích Server nhận liệu phân tích địa sender để truyền lại Có thể server chấp nhận nhiều client thời điểm SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Ví dụ lập trình Socket với TCP TCPClient.java Zo sentence = inFromUser.readLine(); ne C BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); nh Vi en outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); Si clientSocket.close(); } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Ví dụ lập trình Socket với TCP TCPServer.java nh Vi en Zo ne C import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); Si while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); SinhVienZone.com https://fb.com/sinhvienzonevn Chương Socket java om Ví dụ lập trình Socket với TCP TCPServer.java ne C DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); Zo clientSentence = inFromClient.readLine(); nh Vi en capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } Si } SinhVienZone.com https://fb.com/sinhvienzonevn Chương Ví dụ xây dựng ứng dụng WebServer nh Vi en Zo ne C om Chỉ xử lý yêu cầu http Chập nhận phân tích yêu cầu http Lấy file yêu cầu từ hệ thống file server Tạo thơng điệp http trả lời Gửi trả lời phía client Si - SinhVienZone.com https://fb.com/sinhvienzonevn Chương Ví dụ xây dựng ứng dụng WebServer Si nh Vi en Zo ne C om Ví dụ client gửi tới server lệnh GET /hinh.jpeg HTTP/1.1\n\n Server trả client file hinh.jpeg kích thước file SinhVienZone.com https://fb.com/sinhvienzonevn Chương Ví dụ xây dựng ứng dụng WebServer đơn giản om WebServer.java nh Vi en Zo ne C import java.io.*; import java.net.*; import java.util.*; class WebServer{ public static void main(String argv[]) throws Exception { String requestMessageLine; String fileName; ServerSocket listenSocket = new ServerSocket(6789); Socket connectionSocket = listenSocket.accept(); Si BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); SinhVienZone.com https://fb.com/sinhvienzonevn Chương Ví dụ xây dựng ứng dụng WebServer om WebServer.java C requestMessageLine = inFromClient.readLine(); Zo ne StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine); nh Vi en if (tokenizedLine.nextToken().equals("GET")){ fileName = tokenizedLine.nextToken(); if (fileName.startsWith("/") == true ) fileName = fileName.substring(1); Si File file = new File(fileName); int numOfBytes = (int) file.length(); FileInputStream inFile = new FileInputStream (fileName); byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes); SinhVienZone.com https://fb.com/sinhvienzonevn Chương Ví dụ xây dựng ứng dụng WebServer om WebServer.java C outToClient.writeBytes("HTTP/1.0 200 Document Follows\r\n"); Zo ne if (fileName.endsWith(".jpg")) outToClient.writeBytes("Content-Type: image/jpeg\r\n"); nh Vi en if (fileName.endsWith(".gif")) outToClient.writeBytes("Content-Type: image/gif\r\n"); outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n"); Si outToClient.writeBytes("\r\n"); outToClient.write(fileInBytes, 0, numOfBytes); connectionSocket.close(); } else System.out.println("Bad Request Message"); } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho Si nh Vi en Zo ne C om Trong Unix, dịch vụ Echo 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 hai chế độ kết nối khơng kết nối Chương trình TCPEchoClient kế nối tới EchoServer chế độ có kết nối gửi tới ký tự từ ‘0’ tới ‘9’, chờ nhận kết hiển thị chúng lên hình SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho om TCPEchoClient.java Si nh Vi en Zo ne C import java.io.*; import java.net.Socket; public class TCPEchoClient{ public static void main(String args[]){ try { Socket s = new Socket(args[0],7); // Kết nối tới server InputStream is = s.getInputStream(); // Lấy InputStream OutputStream os = s.getOutputStream(); // Lấy OutputStream for (int i='0'; i’9’ den EchoServer os.write(i); // Gủi ký tự sang Server int ch = is.read(); // nhận ký tự từ Server System.out.print((char)ch); // In ký tự hình } //try catch(IOException ie){ System.out.println("Loi: Khong tao duoc socket"); } //catch } //main SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho om STCPChoSer cài đặt chế độ lặp, có kết nối .C STCPEchoServer.java Si nh Vi en Zo ne import java.net.*; import java.io.*; public class STCPEchoServer { public final static int defaultPort = 7; public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(defaultPort); while (true) { try { Socket s = ss.accept(); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); int ch=0; SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho om STCPEchoServer.java Si nh Vi en Zo ne C 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); } } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho om PTCPEchoServer cài đặt chế độ đồng thời, có kết nối .C PTCPEchoServer.java Si nh Vi en Zo ne import java.net.*; import java.io.*; public class PTCPEchoServer { public final static int defaultPort = 7; // public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(defaultPort); //Tạo socket cho server while (true) { try { Socket s = ss.accept(); // RequestProcessing rp = new RequestProcessing(s); // Tạo phần xử lý rp.start(); // Khởi động phần xử lý cho client } catch (IOException e) { System.out.println("Connection Error: "+e); SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho om PTCPEchoServer cài đặt chế độ đồng thời, có kết nối .C PTCPEchoServer.java ne } Zo } } Si nh Vi en catch (IOException e) { System.err.println("Create Socket Error: "+e); } } } SinhVienZone.com https://fb.com/sinhvienzonevn Chương 3 Ví dụ xây dựng chương trình TCPEcho Si nh Vi en Zo ne C om class RequestProcessing extends Thread { Socket channel; //Khai bao socket public RequestProcessing(Socket s){ channel = s; // Socket cua kenh ảo } public void run() { try { OutputStream os = channel.getOutputStream(); InputStream is = channel.getInputStream(); while (true) { int n = is.read(); // Nhan ky tu từ client if (n == -1) break; // os.write(n); // } } catch (IOException e) { System.err.println("Request Processing Error: "+e); } } } SinhVienZone.com https://fb.com/sinhvienzonevn ... clientSocket.close(); } SinhVienZone. com https://fb .com/ sinhvienzonevn Chương Socket java om Ví dụ lập trình Socket với UDP UDPServer .java ne C import java. io.*; import java. net.*; nh Vi en Zo... SinhVienZone. com read reply from clientSocket close clientSocket https://fb .com/ sinhvienzonevn Chương Socket java C om Ví dụ lập trình Socket với TCP TCPClient .java import java. io.*; import java. net.*;... clientSocket.close(); } } SinhVienZone. com https://fb .com/ sinhvienzonevn Chương Socket java om Ví dụ lập trình Socket với TCP TCPServer .java nh Vi en Zo ne C import java. io.*; import java. net.*; class

Ngày đăng: 30/01/2020, 22:43

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan