Giáo trình Lập trình mạng bằng Java - Bách Khoa Forum

pdf 76 trang hoanguyen 2771
Bạn đang xem 20 trang mẫu của tài liệu "Giáo trình Lập trình mạng bằng Java - Bách Khoa Forum", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfgiao_trinh_lap_trinh_mang_bang_java_bach_khoa_forum.pdf

Nội dung text: Giáo trình Lập trình mạng bằng Java - Bách Khoa Forum

  1. Tìm kiếm & download ebook: bookilook.com Bách Khoa Online: hutonline.net Tìm kiếm & download ebook: bookilook.com Bách Khoa Online: hutonline.net
  2. Tìm kiếm & download ebook: bookilook.com Nội dung môn học CHƯƠNG 1: GIỚI THIỆU VỀ TCP/IP CHƯƠNG 2: THIẾT KẾ GIẢI THUẬT CHO CHƯƠNG TRÌNH CLIENT/SERVER CHƯƠNG 3: LẬP TRÌNH MẠNG TRÊN CÁC MÔI TRUỜNG PHỔ DỤNG CHƯƠNG 4: LẬP TRÌNH MẠNG VỚI JAVA Lập trình mạng – Chương 1 1 Nội dung môn học(tt) CHƯƠNG 5: LẬP TRÌNH WEB — CGI CHƯƠNG 6: LẬP TRÌNH WEB VỚI CÁC CÔNG NGHỆ PHỔ BIẾN CHƯƠNG 7: ỨNG DỤNG XML TRONG LẬP TRÌNH MẠNG CHƯƠNG 8: BẢO MẬT DỮ LIỆU TRUYỀN Lập trình mạng – Chương 1 2 Bách Khoa Online: hutonline.net 1
  3. Tìm kiếm & download ebook: bookilook.com Tài liệu tham khảo • [1] Douglas E. Comer, Internetworking with TCP/IP, Prentice-Hall,1993. • [2] W. Richard Stevens, Unix Network Programming, Prentice-Hall,1990. • [3] Arthur Dumas, Programming Winsock, Sams Publishing,1995. • [4] Merlin, Conrad Hughes , Java Network Programming, Manning Publications Co., 1997. • [5] D. Travis Dewire, Second-Generation Client/Server Computing, Mc Graw-Hill, 1997. • [6] John Shapley Gray, Interprocess Comunication in UNIX, Prentice-Hall,1997. • [7] Deitel & Deitel. Java How to program, 3th edition, Prentice-Hall,1999. • [8] Richard Anderson, , Professional Active Server Pages 3.0, Wrox Press, 1999. • [9] Marty Hall, Core Servlet and Java Server Pages, Prentice-Hall PTR, 2000 • [10] MSDN. • [11] Tập tài liệu RFC. Lập trình mạng – Chương 1 3 Lập trình mạng – Chương 1 4 Bách Khoa Online: hutonline.net 2
  4. Tìm kiếm & download ebook: bookilook.com CHƯƠNG 1 GIỚI THIỆU VỀ TCP/IP 1.1 Tổng quát về TCP/IP. 1.2 Các giao thức và dịch vụ trên TCP/IP. 1.3 Khái niệm về Socket. 1.4 Một sốứng dụng mạng. Lập trình mạng – Chương 1 5 1.1 Tổng quát về TCP/IP. OSI TCP/IP Application Applications layer Telnet FTP SMTP DNS SNMP Presentation Session Transport layer TCP UDP Transport (host level) ICMP Internet layer Network (gateway level) ARP IP Data link Network interface Ethernet Token Ring FDDI WANs Physical layer Lập trình mạng – Chương 1 6 Bách Khoa Online: hutonline.net 3
  5. Tìm kiếm & download ebook: bookilook.com 1.1 Tổng quát về TCP/IP (tt) •Một số đặc tính : – Độc lập về hình thái của mạng. – Độc lập về phần cứng của mạng. –Các chuẩn giao thức mở. – Mô hình địa chỉ toàn cầu. –Nền tảng client/server mạnh mẽ. –Các chuẩn về giao thức ứng dụng mạnh mẽ. Lập trình mạng – Chương 1 7 1.1 Tổng quát về TCP/IP (tt) Lập trình mạng – Chương 1 8 Bách Khoa Online: hutonline.net 4
  6. Tìm kiếm & download ebook: bookilook.com 1.1 Tổng quát về TCP/IP (tt) • Địa chỉ Internet: ª Định vị duy nhất một máy ª Chiều dài 32 bit ª Cấu trúc IP (netid, hostid), các máy trên một mạng có netid giống nhau. ª Do NIC cấp ª Cách biểu diễn: 10101100 00011100 00010000 00000101 172 28 16 5 172.28.16.5 Lập trình mạng – Chương 1 9 1.1 Tổng quát về TCP/IP (tt) • Phân lớp địa chỉ: – Để xác định netid (Network Identifier) và hostid (Host Identifier) Lập trình mạng – Chương 1 10 Bách Khoa Online: hutonline.net 5
  7. Tìm kiếm & download ebook: bookilook.com 1.1 Tổng quát về TCP/IP (tt) •Một số địa chỉ IP đặc biệt Lập trình mạng – Chương 1 11 1.1 Tổng quát về TCP/IP (tt) •Lớp Transport application transport network data link network – Cung cấp giao tiếp luận physical lo data link networkg physical ic dataa link lý giữa các processes physicall e n d network trên các hosts khác -e data link n physical network d t data link r nhau a physical n s p network o – Có hai dạng dịch vụ: r data link tphysical •TCP (Transmittion Control application transport Protocol) network data link •UDP (User Datagram physical Protocol) Lập trình mạng – Chương 1 12 Bách Khoa Online: hutonline.net 6
  8. Tìm kiếm & download ebook: bookilook.com 1.1 Tổng quát về TCP/IP (tt) •Lớp Transport (tt) –Mở rộng cách đánh địa chỉ cho process. – Địa chỉ port : xác định ứng dụng mạng trên mỗi máy. – Địa chỉ của một ứng dụng mạng (IP,port) Lập trình mạng – Chương 1 13 1.2 Các giao thức và dịch vụ •Hệ thống tên miền DNS (Domain Name System) – Dùng chuỗi ký tự để đánh địa chỉ, không phân biệt chữ hoa, thường, mỗi thành phần có thể 63 ký tự và tên đầy đủ không dài quá 255, dưới đây gọi là tên. –Tên được đặt theo cây phân cấp – Địa chỉ tài nguyên biểu diễn dạng tên được hình thành từ nó cho đến root Lập trình mạng – Chương 1 14 Bách Khoa Online: hutonline.net 7
  9. Tìm kiếm & download ebook: bookilook.com 1.2 Các giao thức và dịch vụ (tt) •Hệ thống tên miền DNS (tt) Lập trình mạng – Chương 1 15 1.2 Các giao thức và dịch vụ(tt) •Hệ thống tên miền DNS (tt) – Network chỉ hiểu địa chỉ IP (binary) => ánh xạ giữa địa chỉ IP và tên. –Hệ thống tên miền được hiện thực theo distributed database, quản lý theo dạng phân cấp với name servers – Network chỉ hiểu địa chỉ IP (binary) => ánh xạ giữa địa chỉ IP và tên. –Mỗi ứng dụng mạng phải chuyển tên sang địa chỉ IP Lập trình mạng – Chương 1 16 Bách Khoa Online: hutonline.net 8
  10. Tìm kiếm & download ebook: bookilook.com 1.2 Các giao thức và dịch vụ(tt) root name server • DNS (tt) 2 iterated query – Ứng dụng giao tiếp với 3 local name server để hỏi 4 địa chỉ ánh xạ. 7 – Local name server sẽ trả lời hoặc request tiếp local name server intermediate name server dns.eurecom.fr dns.umass.edu 5 6 1 8 authoritative name server dns.cs.umass.edu requesting host surf.eurecom.fr Lập trình mạng – Chương 1gaia.cs.umass.edu 17 1.2 Các giao thức và dịch vụ(tt) • Giao thức ở lớp ứng dụng – Ứng dụng mạng : trao đổi thông tin giữa các processes trên mạng. –Các ứng dụng phải định nghĩa protocol để giao tiếp với nhau. – Protocol qui định thứ tự các thông điệp trao đổi, hành động khi nhận mỗi loại thông điệp. – Ứng dụng cũng phải hiện thực phần giao tiếp với người dùng. Lập trình mạng – Chương 1 18 Bách Khoa Online: hutonline.net 9
  11. Tìm kiếm & download ebook: bookilook.com 1.2 Các giao thức và dịch vụ(tt) • Giao thức ở lớp ứng dụng(tt) – User agent là giao tiếp giữa người sử dụng và ứng dụng mạng. • Web:browser • E-mail: mail reader • streaming audio/video: media player Lập trình mạng – Chương 1 19 1.2 Các giao thức và dịch vụ(tt) • Mô hình mạng client/server – Server : là phần tử thụ động •Chờ yêu cầu từ client, xử lý và trả kết quả cho client – Client : là phần tử chủ động •Kết nối đến server để gởi yêu cầu. •Chờ nhận kết quả trả về và xử lý kết quả. Lập trình mạng – Chương 1 20 Bách Khoa Online: hutonline.net 10
  12. Tìm kiếm & download ebook: bookilook.com 1.2 Các giao thức và dịch vụ(tt) • State và Stateless – State : lưu giữ trạng thái giữa các lần kết nối (request/response). – Stateless : Mỗi lần request/response thì cầu nối hủy bỏ. Không giữ trạng trái trước đó. Lập trình mạng – Chương 1 21 1.3 Khái niệm về Socket. • Socket API – Được giới thiệu ở BSD4.1 UNIX, 1981 – Được ứng dụng khởi tạo, sử dụng hay hủy bỏ – Dùng cơ chế client/server – Cung cấp hai dịch vụ chuyển dữ liệu thông qua socket API: • unreliable datagram • reliable, byte stream-oriented Lập trình mạng – Chương 1 22 Bách Khoa Online: hutonline.net 11
  13. Tìm kiếm & download ebook: bookilook.com 1.3 Khái niệm về Socket(tt) • Socket : – Là môi trường để các process ứng dụng giao tiếp với nhau, process ứng dụng có thể chạy trên cùng một máy hoặc trên hai máy khác nhau. – Được ứng dụng tạo ra và sử dụng tuy nhiên được hệ thống (hệ điều hành) kiểm soát. Lập trình mạng – Chương 1 23 1.3 Khái niệm về Socket(tt) • Socket: “cửa” nằm giữa process ứng dụng và end-end- transport protocol (UCP or TCP) • TCP service: dịch vụ truyền tin cậy chuỗi bytes giữa hai process controlled by controlled by process process application application developer developer socket socket TCP with controlled by controlled by TCP with operating operating buffers, buffers, internet system system variables variables host or host or server server Lập trình mạng – Chương 1 24 Bách Khoa Online: hutonline.net 12
  14. Tìm kiếm & download ebook: bookilook.com 1.3 Khái niệm về Socket(tt) •Lập trình socket với TCP – Client phải kết nối đến server • server process phải chạy trước (phần tử thụ động) • server phải tạo một socket để lắng nghe và chấp nhận các kết nối từ client – Client kết nối đến server bằng cách: •Khởi tạo TCP socket ở local •Xác định IP address, port number của server process và kết nối đến Lập trình mạng – Chương 1 25 1.3 Khái niệm về Socket(tt) •Lập trình socket với TCP(tt) – Sau khi client khởi tạo socket, nó sẽ 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. • Cho phép server chấp nhận nhiều client tại một thời điểm. Lập trình mạng – Chương 1 26 Bách Khoa Online: hutonline.net 13
  15. Tìm kiếm & download ebook: bookilook.com 1.3 Khái niệm về Socket(tt) Server (running on hostid) Client create socket, port=x, for incoming request: welcomeSocket = ServerSocket() TCP wait for incoming create socket, connection request connection setup connect to hostid, port=x connectionSocket = clientSocket = welcomeSocket.accept() Socket() send request using read request from clientSocket connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket Lập trình mạng – Chương 1 27 Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; Create BufferedReader inFromUser = input stream new BufferedReader(new InputStreamReader(System.in)); Create client socket, Socket clientSocket = new Socket("hostname", 6789); connect to server DataOutputStream outToServer = Create new DataOutputStream(clientSocket.getOutputStream()); output stream attached to socket Lập trình mạng – Chương 1 28 Bách Khoa Online: hutonline.net 14
  16. Tìm kiếm & download ebook: bookilook.com Example: Java client (TCP), cont. Create BufferedReader inFromServer = input stream new BufferedReader(new attached to socket InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); Send line to server outToServer.writeBytes(sentence + '\n'); Read line modifiedSentence = inFromServer.readLine(); from server System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Lập trình mạng – Chương 1 29 Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; Create welcoming socket ServerSocket welcomeSocket = new ServerSocket(6789); at port 6789 while(true) { Wait, on welcoming socket for contact Socket connectionSocket = welcomeSocket.accept(); by client BufferedReader inFromClient = Create input new BufferedReader(new stream, attached InputStreamReader(connectionSocket.getInputStream())); to socket Lập trình mạng – Chương 1 30 Bách Khoa Online: hutonline.net 15
  17. Tìm kiếm & download ebook: bookilook.com Example: Java server (TCP), cont Create output stream, attached DataOutputStream outToClient = to socket new DataOutputStream(connectionSocket.getOutputStream()); Read in line clientSentence = inFromClient.readLine(); from socket capitalizedSentence = clientSentence.toUpperCase() + '\n'; Write out line outToClient.writeBytes(capitalizedSentence); to socket } } } End of while loop, loop back and wait for another client connection Lập trình mạng – Chương 1 31 1.3 Khái niệm về Socket(tt) •Lập trình socket với UTP – Cung cấp cơ chế truyền không tin cậy các nhóm các byte (datagrams) giữa client và server. – Không cần thiết lập kết nối giữa client với server. – Sender phải gởi kèm địa chỉ IP và port đích – Server khi nhận dữ liệu sẽ phân tích địa chỉ của sender để truyền lại. Lập trình mạng – Chương 1 32 Bách Khoa Online: hutonline.net 16
  18. Tìm kiếm & download ebook: bookilook.com 1.3 Khái niệm về Socket(tt) •Lập trình socket với UTP(tt) Server (running on hostid) Client create socket, create socket, port=x, for clientSocket = incoming request: DatagramSocket() serverSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read request from serverSocket write reply to serverSocket specifying client read reply from host address, clientSocket port umber close Lập trình mạng – Chương 1clientSocket 33 Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { Create input stream BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Create client socket DatagramSocket clientSocket = new DatagramSocket(); Translate InetAddress IPAddress = InetAddress.getByName("hostname"); hostname to IP address using DNS byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Lập trình mạng – Chương 1 34 Bách Khoa Online: hutonline.net 17
  19. Tìm kiếm & download ebook: bookilook.com Example: Java client (UDP), cont. Create datagram with data-to-send, DatagramPacket sendPacket = length, IP addr, port new DatagramPacket(sendData, sendData.length, IPAddress, 9876); Send datagram clientSocket.send(sendPacket); to server DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); Read datagram clientSocket.receive(receivePacket); from server String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Lập trình mạng – Chương 1 35 Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception Create { datagram socket at port 9876 DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { Create space for received datagram DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); Receive serverSocket.receive(receivePacket); datagram Lập trình mạng – Chương 1 36 Bách Khoa Online: hutonline.net 18
  20. Tìm kiếm & download ebook: bookilook.com Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); Get IP addr InetAddress IPAddress = receivePacket.getAddress(); port #, of sender int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); Create datagram to send to client DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, Write out port); datagram to socket serverSocket.send(sendPacket); } End of while loop, } loop back and wait for } another datagram Lập trình mạng – Chương 1 37 1.4 Một sốứng dụng mạng. • World Wide Web (W W W) – Dùng giao thức http: hypertext transfer protocol htt p r equ – Web’s application layer protocol PC running h est ttp Explorer re spo – Mô hình client/server nse • client: browser gởi yêu cầu, nhận và hiển thị kết quả. st ue eq • server: Web server gởi kết quả p r se Server tt on h sp running cho client đối với mỗi request. re tp NCSA Web ht – http1.0: RFC 1945 server – http1.1: RFC 2068 Mac running Navigator Lập trình mạng – Chương 1 38 Bách Khoa Online: hutonline.net 19
  21. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – http: TCP transport service: • client khởi tạo TCP connection (tạo socket) đến server, port 80 (default) • server chấp nhận kết nối từ client • http messages (application-layer protocol messages) được trao đổi giữa browser (http client) và Web server (http server) • đóng TCP connection Lập trình mạng – Chương 1 39 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – Ví dụ – User đánh địa chỉ URL lên browser 1a. http client tạo TCP connection (tạo socket) đến http server ở 1b. http server ở địa chỉ www.dit.hcmut.edu.vn Port 80 www.dit.hcmut.edu.vn đang chờ đợi kết nối ở port 80, chấp nhận kết nối và notifying đến client 2. http client gởihttp request message (chứa đường dẫn) time thông qua TCP connection socket Lập trình mạng – Chương 1 40 Bách Khoa Online: hutonline.net 20
  22. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – Ví dụ 3. http server nhận yêu cầu, tạo response message (/~phu/courses/net- programming/index.html) trả kết quả,gởi message qua socket 5. http client nhận response 4. http server đóng cầu nốiTCP time message chứa file html và hiển thị. Phân tích file html để tìm các liên kết 6. Lặp lại các bước 1-5 cho mỗi liên kết(object) Lập trình mạng – Chương 1 41 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – Có hai dạng message trong http : request, response – http request message: • ASCII (human-readable format) Lập trình mạng – Chương 1 42 Bách Khoa Online: hutonline.net 21
  23. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – http request message: request line (GET, POST, GET /~phu/index.html HTTP/1.0 HEAD commands) User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg header Accept-language:vn lines (extra carriage return, line feed) Carriage return, line feed indicates end of message Lập trình mạng – Chương 1 43 1.4 Một sốứng dụng mạng(tt) • W W W (tt) – http response message: status line (protocol status code HTTP/1.0 200 OK status phrase) Date: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 header Content-Length: 6821 lines Content-Type: text/html data data data data data data, e.g., requested Lập trình mạng – Chương 1 44 html file Bách Khoa Online: hutonline.net 22
  24. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) client server Authentication goal: control access to usual http request msg server documents 401: authorization req. •stateless:client must present WWW authenticate: authorization in each request • authorization: typically name, password usual http request msg – authorization: header line in + Authorization:line request – if no authorization presented, server usual http response msg refuses access, sends WWW authenticate: usual http request msg header line in response + Authorization:line usual http response msg time Browser caches name & password so that user does not have to repeatedlyLập trình m ạenterng – Chươ it.ng 1 45 1.4 Một sốứng dụng mạng(tt) Cookies client server • server sends “cookie” to client usual http request msg in response mst Set-cookie: 1678453 usual http response + • client presents cookie in later Set-cookie: # requests cookie: 1678453 usual http request msg • server matches presented- cookie: # cookie- cookie with server-stored info spectific – authentication usual http response msg action – remembering user preferences, previous usual http request msg choices cookie- cookie: # spectific usual http response msg action Lập trình mạng – Chương 1 46 Bách Khoa Online: hutonline.net 23
  25. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) server Conditional GET client • Goal: don’t send object if client http request msg has up-to-date stored (cached) If-modified-since: object version not • client: specify date of cached http response modified copy in http request HTTP/1.0 304 Not Modified If-modified-since: • server: response contains no object if cached copy up-to-date: http request msg HTTP/1.0 304 Not Modified If-modified-since: object modified http response HTTP/1.1 200 OK Lập trình mạng – Chương 1 47 1.4 Một sốứng dụng mạng(tt) • File Transfer Protocol (ftp) FTP file transfer FTP FTP user client server interface user at host local file remote file system system –Chuyển file từ local đến server hoặc lấy file từ server về local. –Hoạt động theo cơ chế client/server – FTP server chạy ở port 21. – Tham khảo : RFC 959 Lập trình mạng – Chương 1 48 Bách Khoa Online: hutonline.net 24
  26. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) • FTP (tt) – ftp client giao tiếp đến ftp server qua TCP ở port 21 –Hai cầu nối TCP được thiết lập: • control: exchange commands, responses between client, server. “out of band control” • data: file data to/from server – ftp server hiện thực cơ chế “state”: current directory, earlier authentication Lập trình mạng – Chương 1 49 1.4 Một sốứng dụng mạng(tt) Sample commands: • sent as ASCII text over control channel • USER username • PASS password • LIST return list of file in current directory • RETR filename retrieves (gets) file • STOR filename stores (puts) file onto remote host Lập trình mạng – Chương 1 50 Bách Khoa Online: hutonline.net 25
  27. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) Sample return codes • status code and phrase (as in http) • 331 Username OK, password required • 125 data connection already open; transfer starting • 425 Can’t open data connection • 452 Error writing file Lập trình mạng – Chương 1 51 1.4 Một sốứng dụng mạng(tt) user •Hệ thống E-mail agent mail user server – RFC 821, 822 agent – SMTP: port 25 SMTP mail server user – POP3: port 110 SMTP agent – IMAP: port 143 SMTP mail user server agent user outgoing agent message queue user user mailbox agent Lập trình mạng – Chương 1 52 Bách Khoa Online: hutonline.net 26
  28. Tìm kiếm & download ebook: bookilook.com 1.4 Một sốứng dụng mạng(tt) Hệ thống E-mail – Ví dụ vê SMTP S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: S: 250 alice@crepes.fr Sender ok C: RCPT TO: S: 250 bob@hamburger.edu Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection Lập trình mạng – Chương 1 53 S: +OK POP3 server ready C: user alice S: +OK Ví dụ về POP3 C: pass hungry • client commands: S: +OK user successfully logged on – user: declare username C: list – pass: password S: 1 498 • server responses S: 2 912 S: . – +OK C: retr 1 – -ERR S: S: . client: transaction phase, C: dele 1 • list: list message numbers C: retr 2 • retr: retrieve message by S: number S: . C: dele 2 • dele: delete C: quit • quit S: +OK POP3 server signing off Lập trình mạng – Chương 1 54 Bách Khoa Online: hutonline.net 27
  29. Tìm kiếm & download ebook: bookilook.com CHƯƠNG 2 THIẾT KẾ GIẢI THUẬT CHO CHƯƠNG TRÌNH CLIENT/SERVER 2.1 Giao tiếp socket (Socket Interface ) 2.2 Thiết kế giải thuật cho chương trình client 2.3 Thiết kế giải thuật cho chương trình server Lập trình mạng – Chương 2 55 2.1 Giao tiếp socket • Giao tiếp socket (Socket Interface) là các API dùng cho việc lập trình các ứng dụng mạng. • Socket Interface được định nghĩa trong UNIX BSD, dựa trên việc mở rộng tập các system calls (access files). => Phần này chỉ giới thiệu các khái niệm, ý tưởng và các hàm, kiểu dữ liệu dùng cho lập trình mạng với Socket Interface. Lập trình mạng – Chương 2 56 Bách Khoa Online: hutonline.net 28
  30. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu –Cấu trúc địa chỉ Internet : định nghĩa dạng dữ liệu cấu trúc trong ngôn ngữ C. Cấu trúc này chỉ có 1 field kiểu u_long chứa địa chỉ IP 32 bit. struct in_addr { u_long s_addr; s_addr }; in_addr Hình - cấu trúc địa chỉ Internet Lập trình mạng – Chương 2 57 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu (tt) –Cấu trúc địa chỉ socket : • địa chỉ này lưu trữ địa chỉ IP, chỉ số port, và dạng (family protocol) • Tên cấu trúc là sockaddr_in được biểu diễn ở hình trong slide kế. Trong đó: – sin_len: lưu trữ chiều dài cấu trúc của sockaddr_in – sin_family: dạng protocol của socket – sin_port: chỉ số port – sin_addr: địa chỉ in Internet của socket – sin_zero[8]: không dùng, đặt giá trị = 0 Lập trình mạng – Chương 2 58 Bách Khoa Online: hutonline.net 29
  31. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) sin_len sin_family sin_port sin_addr sin_zero sockaddr_in struct sockaddr_in Hình - Cấu trúc địa chỉ socket { u_char sin_len; u_short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; Lập trình mạng – Chương 2 59 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu (tt) –Cấu trúc socket : • socket được định nghĩa trong hệ điều hành bằng một cấu trúc, được xem như điểm nối để hai procceses giao tiếp với nhau. •Cấu trúc socket gồm 5 field được mô tả như hình trong slide kế: – Family : xác định protocol group – Type : xác loại socket, stream, datagram hay raw socket. – Protocol : là field thường gán giá trị bằng 0 – Local Socket Address và Remote Socket Address : là địa chỉ socket của process cục bộ và từ xa. Lập trình mạng – Chương 2 60 Bách Khoa Online: hutonline.net 30
  32. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) Family Type Protocol sin_len sin_family sin_port sin_addr sin_zero Local Socket Address sin_len sin_family sin_port sin_addr sin_zero Remote Socket Address Socket Lập trình mạng – Chương 2 61 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu (tt) –Loại socket : • Giao tiếp socket định nghĩa 3 loại socket có thể dùng trên môi trường TCP/IP (hình ở slide kế). •Các loại socket gồm: – Stream Socket: dùng cho connection-oriented protocol như TCP. – Datagram Socket: dùng cho connectionless protocol như UDP. – Raw Socket: dùng cho một số protocol của một số ứng dụng đặc biệt, dùng các dịch vụ trực tiếp của lớp IP. Lập trình mạng – Chương 2 62 Bách Khoa Online: hutonline.net 31
  33. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) Application program Stream Datagram socket socket interface interface Raw socket interface TCP UDP IP Physical and datalink layers Hình - Các loại socket Lập trình mạng – Chương 2 63 •Một số cấu trúc dữ liệu (tt) – Thông tin remote host : • Thông tin được lưu trữ trong một cấu trúc hostent được trả về khi ứng dụng muốn ánh xạ địa chỉ tên miền bằng cách gọi hàm gethostbyname(): struct hostent * gethostbyname(const char * hostname); struct hostent { char *h_name; char h_aliases; int h_addrtype; int h_length; char h_addr_list; } Lập trình mạng – Chương 2 64 Bách Khoa Online: hutonline.net 32
  34. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu (tt) – Byte Ordering • Big-Endian Byte Order : byte có trọng số lớn lưu trước. • Little -Endian Byte Order : byte có trọng số nhỏ lưu trước. •Tuỳ cấu trúc của mỗi máy, lưu trữ số theo một trong hai cách trên => khi giao tiếp mạng sẽ không đồng nhất. Lập trình mạng – Chương 2 65 2.1 Giao tiếp socket (tt) •Một số cấu trúc dữ liệu (tt) – Byte Ordering (tt) • Network Byte Order : thứ tự lưu trữ dùng cho giao tiếp mạng. • Giao tiếp socket định nghĩa một số hàm để thực hiện các thao tác chuyển đổi : – htons và htonl : chuyển từ dạng lưu trữ của máy sang Network – ntohs và ntohl : chuyển từ dạng lưu trữ của Network sang dạng lưu trữ của máy. Lập trình mạng – Chương 2 66 Bách Khoa Online: hutonline.net 33
  35. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket –Hàm socket() để tạo mới một socket int socket (int family, int type, int protocol); Hàm này tạo một socket, kết quả trả về là một số nguyên nhận dạng (socket descriptor), nếu có lỗi giá trị trả về là -1. Các thông số : • family: họ socket • type: kiểu socket (stream hay datagram) • protocol: giao thức, thường đặt bằng 0 Lập trình mạng – Chương 2 67 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm bind() để đăng ký với hệ thống int bind (int sockfd, const struct sockaddr_in *localaddr, int localaddrlen); Đăng ký socket đã khởi tạo với địa chỉ socket local. Trả về 0 nếu thành công, -1 nếu thất bại. Các thông số : • sockfd: mô tả socket đã tạo bởi hàm socket() • localaddr:con trỏ chỉ đến địa chỉ socket của local • localaddrlen: chiều dài của địa chỉ socket Lập trình mạng – Chương 2 68 Bách Khoa Online: hutonline.net 34
  36. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm connect() để kết nối đến server int connect(int sockfd, const struct sockaddr_in *serveraddr, int serveraddrlen); Dùng cho chương trình client thiết lập kết nối đến server. Trả về 0 nếu thành công, -1 nếu thất bại. Các thông số : • sockfd: mô tả socket đã tạo bởi hàm socket() • serveraddr:con trỏ địa chỉ socket của server • serveraddrlen: chiều dài của địa chỉ socket server Lập trình mạng – Chương 2 69 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm listen() để kết nối đến server int listen(int sockfd, int backlog); Hàm này dùng cho chương trình server connection-oriented để đặt socket ở trạng thái chờ, lắng nghe kết nối từ phía client. Trả về 0 nếu thành công, -1 nếu thất bại. Các thông số: • sockfd: mô tả socket đã tạo bởi hàm socket() • backlog: số request có thể queued. Lập trình mạng – Chương 2 70 Bách Khoa Online: hutonline.net 35
  37. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm accept() : chấp nhận kết nối từ client đến. int accept(int sockfd, const struct sockaddr_in *clientaddr, int *clientaddrlen); Chấp nhận kết nối từ client, tạo socket mới. Giá trị là một socket descriptor của socket mới. Các thông số : • sockfd: mô tả socket đã tạo bởi hàm socket() • clientaddr:con trỏ địa chỉ socket của client kết nối đến. • clientaddrlen: chiều dài của clientaddr Lập trình mạng – Chương 2 71 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm read() để đọc dữ liệu từ socket int read(int sockfd, const void *buf, int len); Đọc dữ liệu từ connection vào bộ nhớ. Trả về số bytes đọc được nếu thành công, trả về 0 nếu không có dữ liệu, trả về -1 nếu thất bại. Các thông số : • sockfd: mô tả socket đã tạo bởi hàm socket() • buf: con trỏ đến bộ đệm để lưu thông tin đọc được • len: chiều dài của bộ đệm Lập trình mạng – Chương 2 72 Bách Khoa Online: hutonline.net 36
  38. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm write() để ghi dữ liệu int write(int sockfd, const void *buf, int len); Ghi dữ liệu từ bộ nhớ lên connection. Trả về số bytes ghi được nếu thành công, trả về -1 nếu thất bại. Các thông số : • sockfd: mô tả socket đã tạo bởi hàm socket() • buf: con trỏ đến bộ đệm để lưu thông tin đọc được • len: chiều dài của bộ đệm Lập trình mạng – Chương 2 73 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm sendto() để gởi dữ liệu int sendto(int sockfd, const void *buf, int len, int flags, const struct sockaddr_in *toaddr, int toaddrlen); Gởi dữ liệu đến một địa chỉ socket từ xa. Trả về số bytes gởi được nếu thành công, trả về -1 nếu thất bại. Các thông số : • sockfd, buf, len: giống các hàm đã giới thiệu • flags: thường đặt bằng 0 • toaddr, toaddrlen: địa chỉ socket đến và chiều dài. Lập trình mạng – Chương 2 74 Bách Khoa Online: hutonline.net 37
  39. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Hàm recvfrom() để nhận dữ liệu int recvfrom(int sockfd, const void *buf, int len, int flags, const struct sockaddr_in *fromaddr, int fromaddrlen);Nhận dữ liệu từ một địa chỉ socket từ xa. Trả về số bytes gởi được nếu thành công, trả về -1 nếu thất bại. Các thông số : • sockfd, buf, len: giống các hàm đã giới thiệu • fromaddr, fromaddrlen: địa chỉ socket gởi đến và chiều dài. Lập trình mạng – Chương 2 75 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Một số hàm dùng cho việc chuyển đổi u_short htons(u_short host_short); u_short ntohs(u_short network_short); u_long htonl(u_long host_long); u_long ntohl(u_long network_long); char *inet_ntoa(struct in_addr inaddr) int inet_aton(const char *strptr, struct in_addr *addptr) Lập trình mạng – Chương 2 76 Bách Khoa Online: hutonline.net 38
  40. Tìm kiếm & download ebook: bookilook.com 2.1 Giao tiếp socket (tt) • Các hàm dùng cho lập trình socket (tt) –Một số hàm dùng cho việc thao tác dữ liệu void *memset ( void *dest, int chr, int len); void *memcopy ( void *dest, void *src, int len) int memcmp ( const void *first, const void *second, int len) Lập trình mạng – Chương 2 77 2.2 Thiết kế giải thuật cho chương trình client •Giải thuật cho chương trình client dùng TCP –Xác định địa chỉ server –Tạo socket. –Kết nối đến server. –Gởi/nhận dữ liệu theo giao thức lớp ứng dụng đã thiết kế. – Đóng kết nối. Lập trình mạng – Chương 2 78 Bách Khoa Online: hutonline.net 39
  41. Tìm kiếm & download ebook: bookilook.com 2.2 Thiết kế giải thuật cho chương trình client (tt) •Giải thuật cho chương trình client dùng UCP –Xác định địa chỉ server –Tạo socket. – Đăng ký socket với hệ thống. –Gởi/nhận dữ liệu theo giao thức lớp ứng dụng đã thiết kế đến server theo địa chỉ đã xác định. – Đóng kết nối. Lập trình mạng – Chương 2 79 2.3 Thiết kế giải thuật cho chương trình server •Chương trình server có hai loại đơn giản : lặp (iterative) và đồng thời (concurrent). •Hai dạng giao thức chương trình server có thể sử dụng là connection-oriented hoặc connectionless. • Các slide kế tiếp trình bày cách thiết kế giải thuật cho các loại server kết hợp các đặc điểm trên Lập trình mạng – Chương 2 80 Bách Khoa Online: hutonline.net 40
  42. Tìm kiếm & download ebook: bookilook.com 2.3 Thiết kế giải thuật cho chương trình server (tt) •Giải thuật cho chương trình server iterative, connection-oriented: –Tạo socket, đăng ký địa chỉ socket với hệ thống. – Đặt socket ở trạng thái lắng nghe, chờ và sẵn sàng cho việc kết nối từ client. –Chấp nhận kết nối từ client, gởi/nhận dữ liệu theo giao thức lớp ứng dụng đã thiết kế. – Đóng kết nối sau khi hoàn thành, trở lại trạng thái lắng nghe và chờ kết nối mới. Lập trình mạng – Chương 2 81 2.3 Thiết kế giải thuật cho chương trình server (tt) •Giải thuật cho chương trình server iterative, connectionless: –Tạo socket và đăng ký với hệ thống. –Lặp công việc đọc dữ liệu từ client gởi đến, xử lý và gởi trả kết quả cho client theo đúng giao thức lớp ứng dụng đã thiết kế. Lập trình mạng – Chương 2 82 Bách Khoa Online: hutonline.net 41
  43. Tìm kiếm & download ebook: bookilook.com 2.3 Thiết kế giải thuật cho chương trình server (tt) •Các yêu cầu cho concurrent Server: –Tại một thời điểm có thể xử lý nhiều yêu cầu từ client. –Chương trình concurrent server có thể chạy trên máy chỉ có 1 CPU. –Hệ thống phải hỗ trợ multi-tasking Lập trình mạng – Chương 2 83 2.3 Thiết kế giải thuật cho chương trình server (tt) •Giải thuật cho chương trình concurrent, connectionless server: –Tạo socket, đăng ký với hệ thống. –Lặp việc nhận dữ liệu từ client, đối với một dữ liệu nhận, tạo mới một process để xử lý. Tiếp tục nhận dữ liệu mới từ client. – Công việc của process mới : •Nhận thông tin của process cha chuyển đến, lấy thông tin socket •Xử lý và gởi thông tin về cho client theo giao thức lớp ứng dụng đã thiết kế. •Kết thúc. Lập trình mạng – Chương 2 84 Bách Khoa Online: hutonline.net 42
  44. Tìm kiếm & download ebook: bookilook.com 2.3 Thiết kế giải thuật cho chương trình server (tt) •Giải thuật cho chương trình concurrent, connection- oriented server: –Tạo socket, đăng ký với hệ thống. – Đặt socket ở chế độ chờ, lắng nghe kết nối. – Khi có request từ client, chấp nhận kết nối, tạo một process con để xử lý. Quay lại trạng thái chờ, lắng nghe kết nối mới. – Công việc của process mới gồm: •Nhận thông tin kết nối của client. • Giao tiếp với client theo giao thức lớp ứng dụng đã thiết kế. • Đóng kết nối và kết thúc process con. Lập trình mạng – Chương 2 85 2.3 Thiết kế giải thuật cho chương trình server (tt) • Multi-protocol Server (TCP,UDP) – Dùng một chương trình , mở một master socket cho cả TCP và UDP. – Dùng hàm hệ thống (select )để chọn lựa TCP socket hay UDP socket sẵn sàng. – Tùy vào protocol (TCP, UDP ) để xử lý gởi nhận thông điệp theo đúng giao thức của lớp ứng dụng. –Tham khảo thêm RFC 1060 Lập trình mạng – Chương 2 86 Bách Khoa Online: hutonline.net 43
  45. Tìm kiếm & download ebook: bookilook.com 2.3 Thiết kế giải thuật cho chương trình server (tt) • Multi-service Server –Tạo một điểm giao tiếp chung. –Với mỗi request, xem loại dịch vụ cần xử lý. –Với mỗi loại dịch vụ, xử lý riêng biệt –Có thể kết hợp Multi-service và Multi-protocol để thiết kế cho chương trình server. Lập trình mạng – Chương 2 87 CHƯƠNG 3 LẬP TRÌNH MẠNG TRÊN CÁC MÔI TRƯỜNG PHỔ DỤNG 3.1 Lập trình mạng trong UNIX 3.2 Các hàm hỗ trợ lập trình mạng trong UNIX 3.3 Lập trình mạng trong Windows với TCP/IP 3.4 Các hàm hỗ trợ lập trình mạng trong Windows Lập trình mạng – Chương 3 88 Bách Khoa Online: hutonline.net 44
  46. Tìm kiếm & download ebook: bookilook.com 2.1 Lập trình mạng trong UNIX •Lập trình mạng trong môi trường UNIX dùng socket có các hàm giống BSD Socket Interface đã giới thiệu. Lập trình mạng – Chương 3 89 3.2 Các hàm hỗ trợ lập trình mạng trong UNIX • Địa chỉ socket trên Internet và địa chỉ IP: #include struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; struct in_addr{ u_long s_addr; } Lập trình mạng – Chương 3 90 Bách Khoa Online: hutonline.net 45
  47. Tìm kiếm & download ebook: bookilook.com 3.2 Các hàm (tt) • Địa chỉ socket tổng quát: #include struct sockaddr { short sa_family; char sa_data[14]; }; •Họ địa chỉ socket được định nghĩa trong : #define AF_UNIX 1/* local to host (pipes, portals) */ #define AF_INET 2 /* internetwork: UDP, TCP, etc. */ Lập trình mạng – Chương 3 91 3.2 Các hàm (tt) •Cấu trúc địa chỉ máy từ xa. struct hostent { char *h_name; char h_aliases; int h_addrtype; int h_length; char h_addr_list; #define h_addr h_addr_list[0]; } Lập trình mạng – Chương 3 92 Bách Khoa Online: hutonline.net 46
  48. Tìm kiếm & download ebook: bookilook.com 3.2 Các hàm (tt) •Tạo socket: #include #include int socket(int family, int type, int protocol); Ví dụ tạo socket: int sockfd; //Tạo stream socket sockfd = socket(AF_INET,SOCK_STREAM,0); //Tạo datagram socket sockfd = socket(AF_INET,SOCK_DGRAM,0); Lập trình mạng – Chương 3 93 3.2 Các hàm (tt) • Liên kết socket với địa chỉ socket(đăng ký) int bind(int sockfd, struct sockaddr *myaddr, int myaddrlen); Ví dụ bind socket vừa tạo với địa chỉ socket: struct sockaddr_in myaddr; bzero((char*)&myaddr,sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_port = htons(portno); myaddr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sockfd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) error("ERROR on binding"); Lập trình mạng – Chương 3 94 Bách Khoa Online: hutonline.net 47
  49. Tìm kiếm & download ebook: bookilook.com 3.2 Các hàm (tt) • Chuyển socket về trạng thái chờ kết nối. int listen(int sockfd, int backlog); •Chấp nhận yêu cầu kết nối từ client. int accept(int sockfd, struct sockaddr_in *peer, int *addrlen); struct sockaddr_in cli_addr;int newsockfd,clilen; listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); Lập trình mạng – Chương 3 95 3.2 Các hàm (tt) •Hàm kết nối đến server int connect(int sockfd, struct sockaddr *servaddr, int *addrlen); Ví dụ: struct sockaddr_in servaddr; bzero((char*)&servaddr,sizeof(myaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(portno); servaddr.sin_addr.s_addr = inet_addr(serverIP); if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) error(“Can not connect to server"); Lập trình mạng – Chương 3 96 Bách Khoa Online: hutonline.net 48
  50. Tìm kiếm & download ebook: bookilook.com 3.2 Các hàm (tt) • Các hàm truyền nhận dữ liệu: int read(int fd,char *buf, int nbytes); int write(int fd,char *buf,int nbytes); int send(int sockfd, char *buf,int nbytes,int flags); int recv(int sockfd, char *buf,int nbytes,int flags); int sendto(int sockfd, char *buf, int len, int flags, struct sockaddr_in *toaddr, int toaddrlen); int recvfrom(int sockfd, char *buf, int len, int flags, struct sockaddr_in *fromaddr, int fromaddrlen); Lập trình mạng – Chương 3 97 3.2 Các hàm (tt) •Tạo process con để xử lý từng kết nối: int fork(void); int pid; while(1){ newsockfd = accept(sockfd, (struct sockaddr*) &cli_addr, &clilen); if ((pid=fork())==0){ close(sockfd); process(newsockfd); close(newsockfd) exit(0); } close(newsockfd); } Lập trình mạng – Chương 3 98 Bách Khoa Online: hutonline.net 49
  51. Tìm kiếm & download ebook: bookilook.com 3.3 Lập trình mạng trong Windows với TCP/IP • Dùng thư viện WinSock API (Windows Sockets Application Programming Interface ) để hiện thực. •Cần có thư viện WINSOCK.DLL hoặc WINSOCK32.DLL (32-bit Windows ). •Cần include các hàm và cấu trúc từ WINSOCK.H hoặc WINSOCK2.H •Có thể biên dịch dạng dòng lệnh : cl –o dest-file src-file ws2_32.lib Lập trình mạng – Chương 3 99 3.3 Lập trình mạng trong Windows với TCP/IP • WinSock hiện thực Berkeley Sockets Interface trên môi trường Windows. • WinSock có nhiều mở rộng thêm so với Berkeley Sockets. –Hỗ trợ kiến trúc Windows Message-Driven hay event-driven. –Hỗ trợ kiến trúc nonpreemptive của Windows Lập trình mạng – Chương 3 100 Bách Khoa Online: hutonline.net 50
  52. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm hỗ trợ lập trình mạng trong Windows •Khởi tạo WinSock: int WSAStartup(WORD wVersionRequired, LPWSADATA lpWSAData); Ví dụ : WORD wVerRequested = MAKEWORD(0,1); WSADATA wsaData; if(WSAStartup(wVerRequested,&wsaData)!=0){ // process error } Lập trình mạng – Chương 3 101 3.4 Các hàm WinSock (tt) •Kết thúc WinSock int WSAClearup(); •Hàm lấy thông tin lỗi : int WSAGetLastError(void); Lập trình mạng – Chương 3 102 Bách Khoa Online: hutonline.net 51
  53. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) • Cám hàm dùng cho chuyển đổi: –Chuyển địa chỉ IP dạng chuỗi sang nhị phân: unsigned long inet_addr(const char FAR *cp); –Chuyển địa chỉ IP dạng nhị phân sang dạng chuỗi: char FAR *inet_ntoa(struct in_addr in); –Lấy địa chỉ máy cục bộ: int gethostname(char FAR*name,int len); –Lấy địa chỉ máy từ xa: struct hostent FAR *gethostbyname(const char FAR *name); Lập trình mạng – Chương 3 103 3.4 Các hàm WinSock (tt) Ví dụ về lấy địa chỉ PHOSTENT phe = gethostbyname(condlg.m_remotehost); char szTemp[128]; if (phe == NULL) { wsprintf(szTemp,“Not exist '%s'", condlg.m_remotehost); MessageBox(szTemp); return; } memcpy((char FAR *)&(ser_addr.sin_addr), phe- >h_addr,phe->h_length); Lập trình mạng – Chương 3 104 Bách Khoa Online: hutonline.net 52
  54. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) •Hàm tạo socket SOCKET socket ( int af, int type, int protocol ); af :họ socket (thường dùng AF_INET : Internet) type : loại socket (SOCK_STREAM, SOCK_DGRAM) protocol : giao thức, thường đặt = 0 để lấy giá trị default trả về giá trị INVALID_SOCKET nếu có lỗi Ví dụ về hàm tạo socket : ser_sock=socket(AF_INET,SOCK_STREAM,0); if(ser_sock==INVALID_SOCKET) { MessageBox(“Can not create socket"); return TRUE; } Lập trình mạng – Chương 3 105 3.4 Các hàm WinSock (tt) •Hàm đăng ký địa chỉ socket với hệ thống int bind (SOCKET s, const struct sockaddr FAR *addr, int addrlen ); s : mô tả socket đã được khởi tạo. addr : địa chỉ socket. addrlen : chiều dài addr Nếu có lỗi trả về giá trị SOCK_ERROR Lập trình mạng – Chương 3 106 Bách Khoa Online: hutonline.net 53
  55. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) Ví dụ về lệnh bind : // char message[100]; SOCKADDR_IN addr; addr.sin_family=AF_INET; addr.sin_port=htons(2000); addr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(s,(LPSOCKADDR)&addr,sizeof(addr))== SOCKET_ERROR){ wsprintf(message, “Can not bind socket : %d“, WSAGetLastError()); MessageBox(message); return TRUE; } Lập trình mạng – Chương 3 107 3.4 Các hàm WinSock (tt) •Hàm chuyển socket về trạng thái chờ int listen (SOCKET s, int backlog ); backlog : chiều dài hàng đợi trả về giá trị SOCKET_ERROR nếu có lỗi Ví dụ về hàm listen: if(listen(s,5)==SOCKET_ERROR) { wsprintf(message, “Can not listen : %d“, WSAGetLastError()); MessageBox(message); return TRUE; } Lập trình mạng – Chương 3 108 Bách Khoa Online: hutonline.net 54
  56. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) •Hàm chấp nhận kết nối từ client. SOCKET accept (SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen ); s : là mô tả socket của server. addr : con trỏ địa chỉ socket của client kết nối đến. addrlen : chiều dài của addr Lập trình mạng – Chương 3 109 3.4 Các hàm WinSock (tt) Ví dụ về hàm accept : SOCKADDR_IN client_addr;SOCKET cli_s; IN_ADDR clientIP; int len=sizeof(client_addr); cli_S=accept(s,(LPSOCKADDR)&client_addr,&len); if(sock==INVALID_SOCKET) { MessageBox(“Can not eccept"); return TRUE; } else { memcopy(&clientIP,&client_addr.sin_addr.s_addr,4); wsprintf(message,”Client IP= %s and port= %d”, inet_ntoa(clientIP),ntohs(cli_s.sin_port)); } Lập trình mạng – Chương 3 110 Bách Khoa Online: hutonline.net 55
  57. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) • Hàm thiết lập kết nối đến server. int connect (SOCKET s, const struct sockaddr FAR *name, int namelen ); s : socket của chương trình local name : địa chỉ socket của server. namelen : chiều dài của name Trả về giá trị SOCKET_ERROR nếu có lỗi Lập trình mạng – Chương 3 111 3.4 Các hàm WinSock (tt) Ví dụ về hàm connect Î SOCKADDR_IN ser_addr; ser_addr.sin_family=AF_INET; ser_addr.sin_port=htons(2000); ser_addr.sin_addr.s_addr= inet_addr(“172.28.10.20”); if(connect(s,(LPSOCKADDR)&ser_addr, sizeof(ser_addr))==SOCKET_ERROR){ MessageBox(“Can not connect to server”); } Lập trình mạng – Chương 3 112 Bách Khoa Online: hutonline.net 56
  58. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) Lệnh gởi dữ liệu int send (SOCKET s, const char FAR * buf, int len, int flags ); buf : chuỗi dữ liệu cần gởi len : chiều dài của buf flags : thường đặt giá trị 0 Trả về số byte dữ liệu gởi được, nếu lỗi trả về SOCKET_ERROR // char buf[255]; lstrcpy(mesg,”Hello World”); if (send(s,buf,strlen(buf),0) ==SOCKET_ERROR) { MessageBox(“Can not send data"); return; } Lập trình mạng – Chương 3 113 3.4 Các hàm WinSock (tt) int recv ( SOCKET s, char FAR* buf, int len, int flags ); Các thông số tương tự hàm send // #define BUFSIZE (100) char buf[BUFSIZE]; int nByteRecv; nByteRecv = recv(s,buf, BUFSIZE,0); if (nByteRecv == SOCKET_ERROR) { MessageBox(“Error receive data"); return; } // Lập trình mạng – Chương 3 114 Bách Khoa Online: hutonline.net 57
  59. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) • Các hàm dùng cho UDP int sendto (SOCKET s, const char FAR *buf, int len, int flags, const struct sockaddr FAR *to, int tolen); to : địa chỉ socket của process muốn gởi đến int recvfrom ( SOCKET s, char FAR* buf, int len, int flags,const struct sockaddr FAR *from, int FAR *fromlen ); from : địa chỉ socket của process gởi dữ liệu đến Lập trình mạng – Chương 3 115 3.4 Các hàm WinSock (tt) Ví dụ về hàm sendto: #define BUFSIZE (100) char buf[BUFSIZE]; int nByteSend; SOCKADDR_IN to; to.sin_family = AF_INET; to.sin_port = 2000; to.sin_addr.s_addr = inet_addr(“127.0.0.1”); lstrcpy(buf,”Hello World”); nByteSend = sendto(s,buf,lstrlen(buf),0, (LPSOCKADDR)&to,sizeof(to)); if(nByteSend == SOCKET_ERROR ) // Lập trình mạng – Chương 3 116 Bách Khoa Online: hutonline.net 58
  60. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) Ví dụ về hàm recvfrom #define BUFSIZE (100) char buf[BUFSIZE]; int nByteRecv; SOCKADDR_IN from; int fromlen; nByteRecv = recvfrom(s,buf,BUFSIZE,0, (LPSOCKADDR)&from,&fromlen); if(nByteRecv == SOCKET_ERROR ) // Lập trình mạng – Chương 3 117 3.4 Các hàm WinSock (tt) Hàm khai báo nhận event từ network cho socket. int WSAAsyncSelect (SOCKET s, HWND hWnd, unsigned int wMsg, long lEvent); hWnd : cửa sổ nhận sự kiện. wMsg: thông điệp gởi đến. lEvent : sự kiện của socket cần xử lý. • Khi dùng hàm này, socket sẽ được chuyển về trạng thái nonblocking. • Đối với mỗi socket thì chỉ khai báo một thông điệp đến. Có thể khai báo nhiều sự kiện bằng phép OR (|) Lập trình mạng – Chương 3 118 Bách Khoa Online: hutonline.net 59
  61. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) Ví dụ về hàm WSAAsyncSelect BOOL CServerDlg::OnInitDialog() { //s là socket đã được tạo, //đã sử dụng các hàm bind và listen if(WSAAsyncSelect(s,m_hWnd,WM_USER+1, FD_ACCEPT)==SOCKET_ERROR) { return TRUE; } return FALSE; } Lập trình mạng – Chương 3 119 3.4 Các hàm WinSock (tt) • Sau khi dùng hàm WSAAsyncSelect, ta phải khai báo hàm để xử lý biến cố tương ứng. BEGIN_MESSAGE_MAP(CServerDlg, CDialog) //{{AFX_MSG_MAP(CServerDlg) ON_MESSAGE(WM_USER+1,OnAccept) // //}}AFX_MSG_MAP END_MESSAGE_MAP() •Viết hàm xử lý biến cố tương ứng LONG CServerDlg::OnAccept(WPARAM wParam, LPARAM lParam){ } Lập trình mạng – Chương 3 120 Bách Khoa Online: hutonline.net 60
  62. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) •Có thể viết code cho hàm WindowProc để xử lý sự kiện network. LRESULT CServerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { Socket desciptor case WM_USER+1 : OnAccept(); return 1; case WSA_RDCLOSE : if (WSAGETSELECTEVENT(lParam) == FD_READ) Read_Process(wParam); Lập trình mạng – Chương 3 121 3.4 Các hàm WinSock (tt) •Hàm đóng socket : int closesocket ( SOCKET s); Hàm trả về giá trị 0 nếu thành công, nếu thất bại trả về giá trị SOCKET_ERROR Lập trình mạng – Chương 3 122 Bách Khoa Online: hutonline.net 61
  63. Tìm kiếm & download ebook: bookilook.com 3.4 Các hàm WinSock (tt) •Lập trình trên mạng trên Windows bằng MFC : dùng các lớp CWinSock, CDatagramSocket, CStreamSocket. • Tham khảo thêm MSDN Lập trình mạng – Chương 3 123 CHƯƠNG 4 LẬP TRÌNH MẠNG VỚI JAVA 4.1 Giới thiệu ngôn ngữ Java 4.2 Ví dụ về lập trình mạng bằng Java 4.3 Khái niệm Stream và Multithreading 4.4 Thư viện java.net.* Lập trình mạng – Chương 4 124 Bách Khoa Online: hutonline.net 62
  64. Tìm kiếm & download ebook: bookilook.com 4.1 Giới thiệu ngôn ngữ Java • Là ngôn ngữ lập trình hướng đối tượng trong sáng, ra đời vào khoảng năm 1995 do Sun MicroSystems xây dựng. • Là ngôn ngữ thông dịch, chạy trên kiến trúc máy ảo (Java Virtual Machine). •Hỗ trợ mạng mẽ lập trình mạng, bảo mật, multi-thread •Sử dụng thư viện chuẩn JDK Lập trình mạng – Chương 4 125 4.1 Giới thiệu ngôn ngữ Java •JVM hỗ trợ trên nhiều flatform => Java có tính portable “write one-run everywhere”. •Hiện có rất nhiều công cụ hỗ trợ lập trình Java như : JBuilder (5), Visual Café, Microsoft Visual J++ • JDK (Java Development Kit) phiên bản mới 1.4.1 trên Lập trình mạng – Chương 4 126 Bách Khoa Online: hutonline.net 63
  65. Tìm kiếm & download ebook: bookilook.com 4.1 Giới thiệu ngôn ngữ Java •Cài đặt : download chương trình và cài đặt lên máy tính theo hướng dẫn. VD: – Windows : C:\JDK – Unix : /usr/local/jdk • Đặt biến môi trường PATH đến thư mục BIN trong thư mục cài đặt: – Windows : SET PATH=c:\jdk\bin;%PATH% –Unix : • PATH=$PATH:/usr/local/jdk/bin • export PATH Lập trình mạng – Chương 4 127 4.1 Giới thiệu ngôn ngữ Java • Đặt biến môi trường CLASSPATH đến các package có sử dụng trong chương trình. VD: – set CLASSPATH=c:\lib\jdbc.zip;c\lib\xml4j.jar;. •Lập trình : có thể dùng trình soạn thảo bất kỳ, lưu với tên file .java • Biên dịch : – javac file-name.java •Chạy : – java file-name Lập trình mạng – Chương 4 128 Bách Khoa Online: hutonline.net 64
  66. Tìm kiếm & download ebook: bookilook.com 4.2 Ví dụ LTM với Java Chương trình client/server Echo •Chương trình Client 1. //file Client.java 2. import java.net.*; 3. import java.io.*; 4. public class Client{ 5. public static void main(String args[]) throws Exception{ 6. Socket clientsock; 7. DataOutputStream output; 8. BufferedReader input;//bộ đệm đọc dữ liệu 9. clientsock = new Socket("127.0.0.1",2000); 10. input = new BufferedReader(new 11. InputStreamReader(clientsock.getInputStream())); 12. output = new DataOutputStream( 13. clientsock.getOutputStream()); Lập trình mạng – Chương 4 129 4.2 Ví dụ (tt) •Chương trình Client 14. BufferedReader keyInput = new BufferedReader(new 15. InputStreamReader(System.in)); 16. System.out.print("Enter sentence to send to server:"); 17. String data = keyInput.readLine(); 18. output.writeBytes(data+"\n"); 19. int recvByte; 20. System.out.print("Data receicved: "); 21. System.out.println(input.readLine()); 22. clientsock.close(); 23. }//main 24. }//class • Biên dịch: javac Client.java •Thực thi : java Client Lập trình mạng – Chương 4 130 Bách Khoa Online: hutonline.net 65
  67. Tìm kiếm & download ebook: bookilook.com 4.2 Ví dụ (tt) •Chương trình Server 1. //file Server.java 2. import java.net.*; 3. import java.io.*; 4. public class Server{ 5. public static void main(String args[]) throws Exception{ 6. ServerSocket serversock = new ServerSocket(2000); 7. DataOutputStream output;//stream xuat du lieu 8. BufferedReader input;//stream doc du lieu 9. for(;;){ 10. Socket client = serversock.accept(); 11. output = new DataOutputStream( 12. client.getOutputStream()); Lập trình mạng – Chương 4 131 4.2 Ví dụ (tt) •Chương trình Server (tt) 13. input = new BufferedReader(new 14. InputStreamReader(client.getInputStream())); 15. String data = input.readLine(); 16. System.out.println("Recv from client: "+data); 17. output.writeBytes(data+"\n"); 18. output.flush(); 19. }//for 20. } //main 21. }//class •Dịch : javac Server.java •Chạy : java Server Lập trình mạng – Chương 4 132 Bách Khoa Online: hutonline.net 66
  68. Tìm kiếm & download ebook: bookilook.com 4.3 Stream và Multithreading • Khái niệm stream trong ngôn ngữ Java: – Stream : hỗ trợ chức năng truy xuất I/O trong ngôn ngữ Java. – Các công việc truy xuất I/O có thể kể đến như file, kết nối mạng, bàn phím( thiết bị nhập chuẩn), màn hình (tb xuất chuẩn) – Stream là môi trường dẫn dữ liệu, không quan tâm đến định dạng của dữ liệu –Các lớp stream được cung cấp ở gói java.io.*; Lập trình mạng – Chương 4 133 4.3 Stream và Multithreading (tt) • Khái niệm stream (tt): – Được chia ra làm hai loại chính input stream là stream chứa dữ liệu nhập; output stream là stream chứa dữ liệu xuất. –Hai lớp cơ bản trong Java xử lý nhập xuất là InputStream và OutputStream. –Các lớp dẫn xuất thường dùng của InputStream : BufferedInputStream, DataInputStream, ByteArrayInputStream, StringBufferInputStream. Lập trình mạng – Chương 4 134 Bách Khoa Online: hutonline.net 67
  69. Tìm kiếm & download ebook: bookilook.com 4.3 Stream và Multithreading (tt) • Khái niệm stream (tt): –Các lớp dẫn xuất thường dùng của OutputStream : BufferedOutputStream, DataOutputStream, ByteArrayOutputStream –Các lớp thường dùng cho truy xuất tập tin : File, RadomAcessFile – Chi tiết lập trình xem thêm Java docs của JDK Lập trình mạng – Chương 4 135 4.3 Stream và Multithreading (tt) • Thread và Multithread trong Java. – Thread : là một đối tượng có thể chạy nhiều phiên bản đồng thời. – Java hỗ trợ lập trình thread trong bản thân ngôn ngữ. – Có hai cách để tạo Thread : •Xây dựng class extends Thread. • Implements interface Runable Lập trình mạng – Chương 4 136 Bách Khoa Online: hutonline.net 68
  70. Tìm kiếm & download ebook: bookilook.com 4.3 Stream và Multithreading (tt) • Multithreading –Ví dụ : public static void main(String args[]){ // while(true){ Socket newsock = server.accept(); ClientThread ct = new ClientThread(newsock); ct.start(); } } Lập trình mạng – Chương 4 137 4.3 Stream và Multithreading (tt) class ClientThread extends Thread{ Socket sock; public ClientThread(Socket sock){ this.sock = sock; } public void run(){ //xu ly } } Lập trình mạng – Chương 4 138 Bách Khoa Online: hutonline.net 69
  71. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp InetAddress : dùng để thao tác về địa chỉ Internet, các phương thức thường dùng: – public byte[] getAddress(): Returns the raw IP address of this object – public static InetAddress[] getAllByName(String host) throws UnknownHostException – public String getHostAddress() • Returns the IP address string "%d.%d.%d.%d". – public static InetAddress getByName(String host) throws UnknownHostException Lập trình mạng – Chương 4 139 4.4 Thư viện java.net.* •Lớp Socket : dùng cho chương trình client kết nối đến máy chủ – public Socket(String host, int port) throws UnknownHostException, IOException • Creates a stream socket and connects it to the specified port number on the named host. – public Socket(InetAddress address, int port) throws IOException • Creates a stream socket and connects it to the specified port number at the specified IP address. – public Socket(String host, int port, boolean stream) throws IOException • Creates a stream socket and connects it to the specified port number on the named host. Lập trình mạng – Chương 4 140 Bách Khoa Online: hutonline.net 70
  72. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp Socket (tt): – public InputStream getInputStream() throws IOException – public InetAddress getInetAddress() • Returns the address to which the socket is connected. –int getPort() • Returns the remote port to which this socket is connected. – public OutputStream getOutputStream() throws IOException • mReturns an output stream for this socket. Lập trình mạng – Chương 4 141 4.4 Thư viện java.net.* •Lớp ServerSocket : dùng cho chương trình server tao socket và chấp nhận kết nối. – ServerSocket(int port) • Creates a server socket on a specified port. – ServerSocket(int port, int backlog) • Creates a server socket and binds it to the specified local port number, with the specified backlog. – ServerSocket(int port, int backlog, InetAddress bindAddr) • Create a server with the specified port, listen backlog, and local IP address to bind to. Lập trình mạng – Chương 4 142 Bách Khoa Online: hutonline.net 71
  73. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp ServerSocket (tt) – public Socket accept() throws IOException • Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. – public void close() throws IOException • Closes this socket. – public void setSoTimeout(int timeout) throws SocketException • Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. – public String toString() • Returns the implementation address and implementation port of this socket as a String. Lập trình mạng – Chương 4 143 4.4 Thư viện java.net.* •Lớp DatagramSocket : sử dụng cho chương trình dùng UDP – public DatagramSocket() throws SocketException • Constructs a datagram socket and binds it to any available port on the local host machine. – public DatagramSocket(int port) throws SocketException • Constructs a datagram socket and binds it to the specified port on the local host machine. – public DatagramSocket(int port, InetAddress laddr) throws SocketException • Creates a datagram socket, bound to the specified local address. The local port must be between 0 and 65535 inclusive. Lập trình mạng – Chương 4 144 Bách Khoa Online: hutonline.net 72
  74. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp DatagramSocket (tt) : – public void connect(InetAddress address, int port) • Connects the socket to a remote address for this socket. – public void disconnect() • Disconnects the socket. This does nothing if the socket is not connected. – public void receive(DatagramPacket p) throws IOException • Receives a datagram packet from this socket – public void send(DatagramPacket p) throws IOException • Sends a datagram packet from this socket. Lập trình mạng – Chương 4 145 4.4 Thư viện java.net.* •Lớp DatagramPacket : dùng xây dựng các gói tin để trao đổi theo giao thức UDP. – public DatagramPacket(byte[] buf, int length) • Constructs a DatagramPacket for receiving packets of length length. – public DatagramPacket(byte[] buf, int length, InetAddress address, int port) • Constructs a datagram packet for sending packets of length length to the specified port number on the specified host. – public DatagramPacket(byte[] buf, int offset, int length) • Constructs a DatagramPacket for receiving packets of length length, specifying an offset into the buffer Lập trình mạng – Chương 4 146 Bách Khoa Online: hutonline.net 73
  75. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp DatagramPacket (tt) – public InetAddress getAddress() • Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. – public byte[] getData() • Returns the data received or the data to be sent. – public int getLength() • Returns the length of the data to be sent or the length of the data received. – public int getPort() • Returns the port number on the remote host. Lập trình mạng – Chương 4 147 4.4 Thư viện java.net.* •Lớp DatagramPacket (tt) – public void setAddress(InetAddress iaddr) • Sets the IP address of the machine to which this datagram is being sent. – public void setPort(int iport) • Sets the port number on the remote host to which this datagram is being sent. – public void setData(byte[] buf) • Set the data buffer for this packet. – public void setData(byte[] buf, int offset, int length) • Set the data buffer for this packet. Lập trình mạng – Chương 4 148 Bách Khoa Online: hutonline.net 74
  76. Tìm kiếm & download ebook: bookilook.com 4.4 Thư viện java.net.* •Lớp URL : kết nối đến một tài nguyên Internet. – public URL(String spec) throws MalformedURLException • Creates a URL object from the String representation. – public URL(String protocol, String host, String file) throws MalformedURLException • Creates a URL from the specified protocol name, host name, and file name. The default port for the specified protocol is used. – public URL(String protocol, String host, int port, String file) throws MalformedURLException • Creates a URL object from the specified protocol, host, port number, and file. Specifying a port number of -1 indicates that the URL should use the default port for the protocol. Lập trình mạng – Chương 4 149 4.4 Thư viện java.net.* •Lớp URL(tt) – public final Object getContent() throws IOException • Returns the contents of this URL. – public String getFile() • Returns the file name of this URL. – public URLConnection openConnection() throws IOException • Returns a URLConnection object that represents a connection to the remote object referred to by the URL. – public final InputStream openStream() throws IOException • Opens a connection to this URL and returns an InputStream for reading from that connection. Lập trình mạng – Chương 4 150 Bách Khoa Online: hutonline.net 75