Lập tình socket với Java

33 296 1
Lập tình socket với Java

Đ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

Network Programming 1 Lập trình Socket với Java Network Programmin g 2 Nội dung bài học  Lớp InetAddress  Truyền tin với giao thức TCP  TCP Sockets  Ví dụ về máy chủ/khách TCP  Truyền tin với giao thức UDP  Datagram Sockets  Ví dụ về máy chủ/khách UDP Network Programmin g 3 Các classes trong gói java.net  Gói java.net chứa các classes cho phép thực hiện lập trình mạng  ContentHandler  DatagramPacket  DatagramSocket  InetAddress  MulticastSocket  ServerSocket  Socket  SocketImpl  URL  URLConnection  URLEncoder  URLStreamHandler Network Programmin g 4 Exceptions in Java  BindException  ConnectException  MalformedURLException  NoRouteToHostException  ProtocolException  SocketException  UnknownHostException  UnknownServiceException Network Programmin g 5 Lớp InetAddress  Xử lý địa chỉ Internet theo tên và địa chỉ IP  Các hàm chuyển đổi tên/địa chỉ: /* trả về một đối tượng kiểu InetAddress*/ public static InetAddress getByName(String host) throws UnknownHostException /* trả về chuỗi đối tượng kiểu InetAddress*/ public static InetAddress[] getAllByName(String host) throws UnknownHostException public static InetAddress getLocalHost() throws UnknownHostException public boolean isMulticastAddress() public String getHostName() /*trả về tên miền*/ public byte[] getAddress() /*trả về địa chỉ IP dạng chuỗi byte*/ public String getHostAddress() /*trả về địa chỉ IP dạng ký tự*/ public int hashCode() public boolean equals(Object obj) public String toString() Network Programmin g 6 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 chuỗi ký tự nhập từ bàn phím*/ try { InetAddress address = InetAddress.getByName(host); System.out.println("IP address: " + address.toString()); } catch (UnknownHostException e) { System.out.println("Could not find " + host); } } } Network Programmin g 7 Lấy địa chỉ của máy 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!"); } } } Network Programmin g 8 Truyền tin với giao thức TCP TCP client TCP server socket() ServerSocket () ServerSocket. accept() BufferedReader. readLine() PrintWriter. println() read() connect() write() close() Connection request EOF Wait next request Process request data (request) data (reply) BufferedReader. readLine() ServerSocket. close() Network Programmin g 9 Lớp Java.net.Socket  Lớp cơ bảncủa Java để thực hiện truyền tin TCP phía máy khách  Thiết lập hoặc ngắt kết nối và thiết lập các tùy chọn socket  Kết nối được thiết lập khi khởi tạo đối tượng  Mỗi đối tượng Socket được gán với một máy chủ duy nhất  Để kết nối với một máy chủ khác, phải tạo ra một đối tượng Socket mới 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 Network Programmin g 10 The Java.net.Socket Class (2)  Gửi và nhận dữ liệu được thực hiện thông qua dòng dữ liệu xuất/nhập  Có một số hàm để lấy đối tượng là dòng nhập cho một socket và dòng xuất cho socket đó. public InputStream getInputStream() throws IOException public OutputStream getOutputStream() throws IOException  Lấy thông tin về một Socket  public InetAddress getInetAddress( )  public int getPort( )  public int getLocalPort( )  public InetAddress getLocalAddress( )  Đóng socket:  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 [...]... Lớp DatagramSocket  Tạo datagram socket để nhận DatagramPacket   Không có phân biệt giữa socket máy khách và socket máy chủ Một DatagramSocket có thể gửi cho nhiều địa chỉ đích khác nhau   Địa chỉ đích được lưu tại DatagramPacket public DatagramSocket() throws SocketException public DatagramSocket(int port) throws SocketException public DatagramSocket(int port, InetAddress laddr) throws SocketException... khách kết nối đến, hàm accept( ) sẽ trả về một đối tượng Socket public void close() throws IOException  Đóng socket máy chủ và giải phóng cổng chờ Network Programmin 15 TCP Sockets MÁY CHỦ: 1 Tạo một đối tượng ServerSocket ServerSocket servSocket = new ServerSocket(1234); 2 3 4 5 Đưa máy chủ vào trạng thái chờ Socket link = servSocket.accept(); Thiết lập các dòng xuất/nhập dữ liệu Gửi và nhận dữ liệu out.println(awaiting... 13 Lớp Java. net.ServerSocket  Lớp java. net.ServerSocket bao gồm      Các hàm khởi tạo đối tượng ServerSocket Các hàm chờ kết nối Các hàm thiết lập các loại tùy chọn socket máy chủ Các hàm thường dùng khác như toString( ) Có bốn hàm khởi tạo ServerSocket cho phép thiết lập cổng, kích thước hàng đợi của các yêu cầu kết nối và network interface gán cho tiến trình máy chủ     public ServerSocket(int... gói dữ liệu dgramSocket.send(outPacket) Đóng DatagramSocket: dgramSocket.close(); Network Programmin 27 Các bước thiết lập truyền tin UDP – Máy khách (1) 1 2 3 4 Tạo đối tượng kiểu DatagramSocket DatagramSocket dgramSocket = new DatagramSocket; Tạo gói dữ liệu UDP xuất DatagramPacket outPacket = new DatagramPacket( message.getBytes(), message.length(), host, port); Gửi gói dữ liệu dgramSocket.send(outPacket)...TCP Sockets MÁY KHÁCH: 1 Thiết lập kết nối đến máy chủ Socket link = new Socket( inetAddress.getLocalHost(),1234); 2 3 4 Thiết lập các dòng xuất/nhập dữ liệu Gửi và nhận dữ liệu Đóng kết nối Network Programmin 11 Ví dụ: DaytimeClient .java import java. net.*; import java. io.*; public class DaytimeClient { public static void main(String[]...  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 Programmin 14 Lớp Java. net.ServerSocket - Chấp nhận và đóng kết nối  public Socket accept() throws IOException    Dừng thực hiện của tiến... Programmin 25 Các bước thiết lập truyền tin UDP - MÁY CHỦ 1 2 3 4 Khởi tạo một đối tượng kiểu DatagramSocket DatagramSocket dgramSocket = new DatagramSocket(1234); Tạo buffer cho dòng dữ liệu nhập byte[] buffer = new byte[256]; Tạo đối tượng kiểu DatagramPacket cho dòng dữ liệu nhập DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length); Chờ dòng dữ liệu nhập dgramSocket.receive(inPacket)... out.write(buff,0,bytesread); } s.close(); } } Network Programmin 19 Lớp java. net.DatagramPacket   Biểu diễn các gói dữ liệu UDP Cung cấp các hàm    Lấy và thiết lập địa chỉ đích/nguồn từ/vào tiêu đề IP Lấy và thiết lập cổng giao tiếp đích/nguồn Nhận và thiết lập gói dữ liệu UDP Network Programmin 20 Hàm khởi tạo DatagramPacket Với bên nhận: DatagramPacket(byte[] buf, int len); Với bên gửi: DatagramPacket( byte[] buf, int... 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... Trả về địa chỉ IP mà socket đang sử dụng Network Programmin 24 Điều khiển kết nối – với Java 1.2  public void connect(InetAddress host, int port)       Gửi và nhận gói tin từ một điạ chỉ IP và cổng được định trước Không giống như kết nối TCP public void disconnect( ) public int getPort( ) public InetAddress getInetAddress( ) public InetAddress getRemoteSocketAddress( ) // Java 1.4 Network Programmin . Socket  public void close() throws IOException  Đóng socket máy chủ và giải phóng cổng chờ Network Programmin g 16 TCP Sockets MÁY CHỦ: 1. Tạo một đối tượng ServerSocket ServerSocket servSocket. Programmin g 14 Lớp Java. net.ServerSocket  Lớp java. net.ServerSocket bao gồm  Các hàm khởi tạo đối tượng ServerSocket  Các hàm chờ kết nối  Các hàm thiết lập các loại tùy chọn socket máy chủ  Các. mạng  ContentHandler  DatagramPacket  DatagramSocket  InetAddress  MulticastSocket  ServerSocket  Socket  SocketImpl  URL  URLConnection  URLEncoder  URLStreamHandler Network Programmin g 4 Exceptions in Java  BindException  ConnectException  MalformedURLException  NoRouteToHostException  ProtocolException  SocketException  UnknownHostException  UnknownServiceException

Ngày đăng: 09/05/2014, 08:27

Từ khóa liên quan

Mục lục

  • Slide 1

  • Slide 2

  • Slide 3

  • Slide 4

  • Slide 5

  • Slide 6

  • Slide 7

  • Slide 8

  • Slide 9

  • Slide 10

  • Slide 11

  • Slide 12

  • Slide 13

  • Slide 14

  • Slide 15

  • Slide 16

  • Slide 17

  • Slide 18

  • Slide 19

  • Slide 20

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

Tài liệu liên quan