Presentation is loading. Please wait.

Presentation is loading. Please wait.

Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies) Edgars Celms, Mārtiņš Opmanis Latvijas Universitātes Matemātikas.

Similar presentations


Presentation on theme: "Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies) Edgars Celms, Mārtiņš Opmanis Latvijas Universitātes Matemātikas."— Presentation transcript:

1 Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies) Edgars Celms, Mārtiņš Opmanis (askola@mii.lu.lv) Latvijas Universitātes Matemātikas un informātikas institūts 2007, Rīga, Latvija

2 Tīklošanas iespējas valodā Java (networking) “Java™ How to Program, Sixth Edition”  Chapter 24. Networking Darbošanās ar URL Datu lasīšana no Web Servera Vienkārša servera izveidošana izmantojot stream sockets Vienkārša klienta izveidošana izmantojot stream sockets Klienta/Servera sadarbība izmantojot stream sockets savienojumu Bezsavienojuma (connectionless) Klienta/Servera sadarbība izmantojot datagrams Klienta/Servera Tic-Tac-Toe izmantojot daudzpavedienu (multithreading) serveri

3 Ievads Pakotne java.net – satur klases, kuras nodrošina darbu ar tīkla servisiem  Plūsmas bāzēta sadarbība (stream-based communications) Lietojumprogrammas “tīklošanos” uztver kā datu plūsmas (streams of data) Konekciju bāzēti protokoli Izmanto TCP (Transmission Control Protocol)  Pakešu bāzēta sadarbība (packet-based communications) Tiek sūtītas individuālas paketes Bezkonekciju servisi (connectionless service) Izmanto UDP (User Datagram Protocol) Klienta-servera attiecība (client-server relationship)  Klients pieprasa veikt kādas darbības  Serveris izpilda darbības un atbild klientam  Pieprasījuma-atbildes modelis (request-response model) Populārākā implementācija: tīmekļa pārlūkprogrammas (web browsers) un tīmekļa serveri (web servers)

4 Dažas piezīmes I (Software Engineering Observation) Performance tip. Connectionless services generally offer greater performance but less reliability than connection-oriented services. Portability tip. TCP, UDP and related protocols enable a great variety of heterogeneous computer systems (i.e., computer systems with different processors and different operating systems) to intercommunicate.

5 Darbošanās ar URLiem (manipulating URLs) HyperText Transfer Protocol (HTTP)  Izmanto URI (Uniform Resource Identifiers) lai identificētu datus URL (Uniform Resource Locators)  URI – specificē dokumentu atrašanās vietu  Var referencēt failus, folderus, kā arī dažādus saliktus (complex) objektus. HTML dokuments SiteSelector.html  applet elements  param birka (tag) name atribūts value atribūts

6 HTML document to load SiteSelector applet Declare param tags for the applet, each parameter has a name and a value

7 Import classes in package java.net Import interface AppletContext from package java.net

8 When the user selects one of the Web sites listed in siteChooser, the program calls method valueChanged Pass the selected site name (the key) to HashMap method get, which locates and returns a reference to the corresponding URL (the value) Get a reference to an AppletContext object that represents the applet container Display in the current browser window the resource associated with URL newDocument

9 Use Applet method getParameter to obtain a Web site title Use Applet method getParameter to obtain the Web site location Use the location as the value of a new URL object If the location passed to the URL constructor is invalid, the URL constructor throws a MalformedURLException

10 Use Applet method getParameter to obtain the next site title

11 Darbošanās ar URLiem ( manipulating URLs ) HTML freimi (frames)  Ir arī iespēja specificēt freimu showDocument metodē _blank _self _top

12 Dažas piezīmes II (Software Engineering Observation) The applet in example must be run from a Web browser, such as Mozilla or Microsoft Internet Explorer, to see the results of displaying another Web page. The appletviewer is capable only of executing applets – it ignores all other HTML tags. If the Web sites in the program contained Java applets, only those applets would appear in the appletviewer when the user selected a Web site. Each applet would execute in a separate appletviewer window.

13 Datu lasīšana no Web Servera Swing GUI komponente JEditorPane  Spēj apstrādāt gan parastu tekstu (plain text), gan arī HTML- formatētu tekstu  Piemērs, ReadServerFile.java – darbojas kā vienkārša tīmekļa pārlūkprogramma (web browser) Attēlo failus no tīmekļa servera pēc uzdotā URI HyperlinkEvents notikumi  Notiek brīdī, kad lietotājs uzklikšķina uz hipersaites (hyperlink)  Trīs notikumu tipi  HyperlinkEvent.EventType.ACTIVATED  HyperlinkEvent.EventType.ENTERED  HyperlinkEvent.EventType.EXITED JEditorPane ģenerē HyperlinkEvents tikai un vienīgi tad, ja tā ir nemodificējama (uneditable).

14 Import JEditPane from package javax.swing, import HyperlinkEvent and HyperlinkListener from package javax.swing.event Declare JEditorPane contentsArea, which will be used to display the contents of the file

15 Create JEditorPane using the no-argument constructor Set JEditorPane editable property to false Register a HyperlinkListener to handle HyperlinkEvents, which occur when the user clicks a hyperlink in the JEditorPane Method hyperlinkUpdate is called when a HyperlinkEvent occurs Use HyperlinkEvent method getEventType to determine the type of the HyperlinkEvent Use HyperlinkEvent method getURL to obtain the URL represented by the hyperlink

16 Invoke JEditorPane method setPage to download the document specified by location and display it in the JEditPane

17

18 Vienkārša servera izveidošana izmantojot stream sockets Pieci soļi vienkārša servera izveidošanai valodā Java  1. Solis: Jāizveido ServerSocket objekts ServerSocket server = new ServerSocket( portNumber, queueLength ); Jāpiereģistrē pieejamais (brīvais) ports Jāspecificē maksimālais klientu skaits (queue length). Porta numuru klients izmanto, lai atrastu servera aplikāciju uz servera, tiek saukts arī par – Handshake point Jāsasaista serveris ar portu (binding the server to the port)  Tikai viena servera aplikācija var būt piesaistīts specifiskam portam  2. Solis: Serveris klausās klienta pieslēgumus Serveris nepārtraukti (indefinitely) klausās potenciālos klienta pieslēgumus Socket connection = server.accept(); Izmantojot Socket objektu serveris sadarbojas ar klientu  The interactions with the client actually occur at a different server port from the handshake point. This allows the port specified in Step 1 to be used again in a multithreaded server to accept another client connection.  3. Solis: Datu sūtīšana un saņemšana OutputStream datu sūtīšanai un InputStream datu saņemšanai  Metode getOutputStream atgriež Socket ’a OutputStream  Metode getInputstream atgriež Socket ’a InputStream  4. Solis: Procesa fāze Serveris un klients sadarbojas izmantojot plūsmas  5. Solis: Slēdz plūsmas un savienojumus Metode close

19 Dažas piezīmes III (Software Engineering Observation) Port numbers can be between 0 and 65,535. Most operating systems reserve port numbers below 1024 for system services (e.g., e-mail and World Wide Web servers). Generally, these ports should not be specified as connection ports in user programs. In fact, some operating systems require special access privileges to bind to port numbers below 1024. With sockets, network I/O appears to Java programs to be similar to sequential file I/O. Sockets hide much of the complexity of network programming from the programmer. With Java’s multithreading, we can create multithreaded servers that can manage many simultaneous connections with many clients. This multithreaded-server architecture is precisely what popular network servers use. A multithreaded server can take the Socket returned by each call to accept and create a new thread that manages network I/O across that Socket. Alternatively, a multithreaded server can maintain a pool of threads (a set of already existing threads) ready to manage network I/O across the new Sockets as they are created. Performance tip.In high-performance systems in which memory is abundant, a multithreaded server can be implemented to create a pool of threads that can be assigned quickly to handle network I/O across each new Socket as it is created. Thus, when the server receives a connection, it need not incur the overhead of thread creation. When the connection is closed, the thread is returned to the pool for reuse.

20 Vienkārša klienta izveidošana izmantojot stream sockets Četri soļi vienkārša klienta izveidošanai valodā Java  1. Solis: Lai pieslēgtos serverim ir jāizveido Socket objekts Socket connection = new Socket ( serverAddress, port );  2. Solis: Datu sūtīšana un saņemšana OutputStream datu sūtīšanai un InputStream datu saņemšanai  Metode getOutputStream atgriež Socket’a OutputStream  Metode getInputstream atgriež Socket’a InputStream  4. Solis: Procesa fāze Klients un serveris sadarbojas izmantojot plūsmas  4. Solis: Slēdz plūsmas un savienojumus

21 Klienta/Servera sadarbība izmantojot stream sockets savienojumu Klienta/servera chat lietojumprogramma  Izmanto stream sockets  Serveris gaida klienta pieslēguma mēģinājumu  Klients pieslēdzas serverim Sūta un saņem ziņojumus  Klients vai serveris izbeidz savienojumu  Serveris gaida nākamo klienta pieslēgumu

22 Import ServerSocket and Socket from package java.net Declare Socket connection which connects to the client Declare ServerSocket server which waits for client connection

23

24 Create ServerSocket at port 12345 with queue of length 100 After the connection is established, obtain references to the streams for the connection Send the initial connection message to the client and process all messages received from the client Wait for a client connection

25 Obtain Socket ’s OutputStream and use it to initialize ObjectOutputStream Use ServerSocket method accept to wait for a connection from a client Output the host name of the computer that made the connection using Socket method getInetAddress and InetAddress method getHostName Method flush empties output buffer and sends header information

26 Obtain Socket ’s InputStream and use it to initialize ObjectInputStream Use ObjectInputStream method readObject to read a String from client

27 Method closeConnection closes streams and sockets Invoke Socket method close to close the socket Use ObjectOutputStream method writeObject to send a String to client

28

29

30 Populārākās programmēšanas kļūdas I (Common Programming Error) Specifying a port that is already in use or specifying an invalid port number when creating a ServerSocket results in a BindException.

31 Dažas piezīmes IV (Software Engineering Observation) When using an ObjectOutputStream and ObjectInputStream to send and receive data over a network connection, always create the ObjectOutputStream first and flush the stream so that the client’s ObjectInputStream can prepare to receive the data. This is required only for networking applications that communicate using ObjectOutputStream and ObjectInputStream. Performance tip.A computer’s input and output components are typically much slower than its memory. Output buffers typically are used to increase the efficiency of an application by sending larger amounts of data fewer times, thus reducing the number of times an application accesses the computer’s input and output components.

32

33

34

35 Create a Socket that will connect with port 12345 on the server Use InetAddress static method getByName to obtain an InetAdress object containing the IP address specified as a command-line argument to the application Display a message indicating the name of the server computer to which the client has connected Method flush empties output buffer and sends header information Obtain Socket ’s OutputStream and use it to initialize ObjectOutputStream

36 Read a String object from server Invoke Socket method close to close the socket

37 Use ObjectOutputStream method writeObject to send a String to server

38

39

40

41 Bezsavienojuma (connectionless) klienta/servera sadarbība izmantojot datagrams Bezsavienojuma sadarbība izmantojot datagrams  Netiek uzturēts savienojums starp datoriem  Sadala ziņojumus atsevišķās daļās un sūta kā paketes  Ziņojumi var pienākt noteiktā secībā, bez secības, vai arī nepienākt vispār  Saņēmējam ir jāvar sakārtot paketes pareizā secībā un izlasīt

42 Use a DatagramSocket as our server

43 Use the DatagramSocket constructor that takes an integer port number argument to bind the server to a port where it can receive packets from clients Create a DatagramPacket in which a received packet of information can be stored Use DatagramSocket method receive to wait for a packet to arrive at the server

44 Use DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sent Use DatagramPacket method getPort to obtain the port number through which the host computer sent the packet Use DatagramPacket method getLength to obtain the number of bytes of data sent Use DatagramPacket method getData to obtain an byte array containing the data Create a DatagramPacket, which specifies the data to send, the number of bytes to send, the client computer’s Internet address and the port where the client is waiting to receive packets

45 Use method send of DatagramSocket to send the packet over the network

46 Server window after packet of data is received from client

47

48 Create a DatagramPacket and initialize it with the byte array, the length of the string that was entered by the user, the IP address to which the packet is to be sent and the port number at which the server is waiting Use DatagramPacket method send to send the packet Convert the String to a byte array

49 Create a DatagramSocket for sending and receiving packets

50 Create a DatagramPacket to store received information Use DatagramPacket method getAddress to obtain the host name of the computer from which the packet was sent Use DatagramPacket method getPort to obtain the port number through which the host computer sent the packet Use DatagramPacket method getLength to obtain the number of bytes of data sent Use DatagramPacket method getData to obtain an byte array containing the data

51

52 Client window after sending packet to Server and receiving packet back from Server

53 Populārākās programmēšanas kļūdas II (Common Programming Error) Specifying a port that is already in use or specifying an invalid port number when creating a DatagramSocket results in a SocketException.

54 Klienta/Servera Tic-Tac-Toe izmantojot daudzpavedienu (multithreading) serveri Tuvāk neapskatīsim.  Sīkāk skat. “Java™ How to Program, Sixth Edition” 24.8. Client/Server Tic-Tac-Toe Using a Multithreaded Server With Java’s multithreading, we can create multithreaded servers that can manage many simultaneous connections with many clients. This multithreaded-server architecture is precisely what popular network servers use. A multithreaded server can take the Socket returned by each call to accept and create a new thread that manages network I/O across that Socket. Alternatively, a multithreaded server can maintain a pool of threads (a set of already existing threads) ready to manage network I/O across the new Sockets as they are created. Ja ir interese, tad varat izpētīt arī kā ir realizēts “ DeitelMessenger Serveris un Klients”  Sīkāk skat. “Java™ How to Program, Sixth Edition” 24.10. Case Study: DeitelMessenger Server and Client

55 Klienta/Servera Tic-Tac-Toe izmantojot daudzpavedienu (multithreading) serveri

56 Jautājumi ?


Download ppt "Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies) Edgars Celms, Mārtiņš Opmanis Latvijas Universitātes Matemātikas."

Similar presentations


Ads by Google