1 / 83

Networking

Networking. Introduction. In this chapter Swing GUI component JEditorPane (view HTML docs) Socket-based communications View networking like file I/O Stream sockets When connection in place, data flows in continuous streams TCP protocol Preferred. Manipulating URLs.

lfitzgerald
Download Presentation

Networking

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Networking

  2. Introduction • In this chapter • Swing GUI component JEditorPane (view HTML docs) • Socket-based communications • View networking like file I/O • Stream sockets • When connection in place, data flows in continuous streams • TCP protocol • Preferred

  3. Manipulating URLs • Internet has many protocols • HTTP protocol • Basis of World Wide Web • Uses URLs to locate data • Can represent files, directories, complex lookups • Java can manipulate URLs easily • Example Applet • Display list of web sites with JList • Get parameters from HTML file • Change to web site user selects • Applet must be run in Explorer or Communicator (not appletviewer)

  4. 1 <APPLET CODE= "SiteSelector.class" WIDTH=300 HEIGHT=75> 67 sites.put( title, url ); 2 <PARAM NAME="title0" VALUE="Java Home Page"> 3 <PARAM NAME="location0" VALUE="http://java.sun.com/"> 26 sites = new Hashtable(); 60 title = getParameter( "title" + counter ); 63 location = getParameter( "location" + counter ); 66 url = new URL( location ); Manipulating URLs • getParameter( name ) • Returns parameter from HTML document • Hashtable • Stores key/value pairs (method put)

  5. 36 siteChooser.addListSelectionListener( 37 new ListSelectionListener() { 38 public void valueChanged( ListSelectionEvent e ) 39 { 40 Object o = siteChooser.getSelectedValue(); 41 URL newDocument = (URL) sites.get( o ); 42 AppletContext browser = getAppletContext(); 43 browser.showDocument( newDocument ); 44 } 45 } Manipulating URLs • ListSelectionListener • Method valueChanged (event handler) • getSelectedValue • Returns selected item • Hashtable method get( key ) • Returns value as Object reference • Cast to URL reference

  6. 36 siteChooser.addListSelectionListener( 37 new ListSelectionListener() { 38 public void valueChanged( ListSelectionEvent e ) 39 { 40 Object o = siteChooser.getSelectedValue(); 41 URL newDocument = (URL) sites.get( o ); 42 AppletContext browser = getAppletContext(); 43 browser.showDocument( newDocument ); 44 } 45 } Manipulating URLs • getAppletContext • Returns reference to AppletContext object • Represents browser executing applet • showDocument( URL ) • Loads URL

  7. 1 <APPLET CODE= "SiteSelector.class" WIDTH=300 HEIGHT=75> 2 <PARAM NAME="title0" VALUE="Java Home Page"> 3 <PARAM NAME="location0" VALUE="http://java.sun.com/"> 4 <PARAM NAME="title1" VALUE="Deitel"> 5 <PARAM NAME="location1" VALUE="http://www.deitel.com/"> 6 <PARAM NAME="title2" VALUE="Gamelan"> 7 <PARAM NAME="location2" VALUE="http://www.gamelan.com/"> 8 <PARAM NAME="title3" VALUE="JavaWorld"> 9 <PARAM NAME="location3" VALUE="http://www.javaworld.com/"> Hashtables store key/value pairs (more chapter 23). 10 </APPLET> 11 // Fig. 21.1: SiteSelector.java 12 // This program uses a button to load a document from a URL. 13 import java.net.*; 14 import java.util.*; 15 import javax.swing.*; 16 import javax.swing.event.*; 17 import java.awt.*; 18 import java.applet.AppletContext; 19 20 public class SiteSelector extends JApplet { 21 private Hashtable sites; 22 private Vector siteNames; 23 24 public void init() 25 { 26 sites = new Hashtable(); 27 siteNames = new Vector(); 28 29 getSitesFromHTMLParameters(); 1. HTML file with parameters ------------------- 1. import 1.1 Class SiteSelector (extends JApplet) 1.2 Hashtable

  8. 34 35 final JList siteChooser = new JList( siteNames ); 36 siteChooser.addListSelectionListener( Get selected site, cast to URL. Display in browser. 37 new ListSelectionListener() { 38 public void valueChanged( ListSelectionEvent e ) 39 { 40 Object o = siteChooser.getSelectedValue(); 41 URL newDocument = (URL) sites.get( o ); 42 AppletContext browser = getAppletContext(); 43 browser.showDocument( newDocument ); 44 } 45 } 46 ); 47 c.add( new JScrollPane( siteChooser ), 48 BorderLayout.CENTER ); 49 } 50 51 private void getSitesFromHTMLParameters() 52 { 53 // look for applet parameters in the HTML document 54 // and add sites to Hashtable 55 String title, location; 56 URL url; 57 int counter = 0; 58 30 31 Container c = getContentPane(); 32 c.add( new JLabel( "Choose a site to browse" ), 33 BorderLayout.NORTH ); 1.3 GUI 1.4 Event handler 1.5 getSelectedValue 1.6 get 1.7 getAppletContext 1.8 showDocument 2. getSitesFromHTML Parameters

  9. 67 sites.put( title, url ); 68 siteNames.addElement( title ); 69 } 70 catch ( MalformedURLException e ) { Add key/value pair to hashtable. 71 e.printStackTrace(); 72 } 73 } 74 else 75 break; 76 77 ++counter; 78 } 79 } 80 } 59 while ( true ) { 60 title = getParameter( "title" + counter ); 61 62 if ( title != null ) { 63 location = getParameter( "location" + counter ); 64 65 try { 66 url = new URL( location ); 2.1 getParameter 2.2 put

  10. Reading a File on a Web Server • Reading files from a web server • JEditorPane (javax.swing) • Can display text and HTML • Applets can only read files from original server

  11. 34 contents.addHyperlinkListener( 35 new HyperlinkListener() { 36 public void hyperlinkUpdate( HyperlinkEvent e ) 58 contents.setPage( location ); 32 contents = new JEditorPane(); 33 contents.setEditable( false ); Reading a File on a Web Server • JEditorPane • Method setPage( locationString ) • Download and display page • Hyperlinks • Text, images, GUI components that access another document on web • Generates HyperLinkEvent, notifies HyperLinkListeners

  12. 36 public void hyperlinkUpdate( HyperlinkEvent e ) 37 { 38 if ( e.getEventType() == 39 HyperlinkEvent.EventType.ACTIVATED ) 40 getThePage( e.getURL().toString() ); 41 } Reading a File on a Web Server • Method getEventType • Inner class EventType has three types • ACTIVATED - clicked • ENTERED - mouse over hyperlink • EXITED - mouse leaves hyperlink • Method getURL - returns URL of link

  13. 68 setCursor( Cursor.getPredefinedCursor( 69 Cursor.DEFAULT_CURSOR ) ); 54 setCursor( Cursor.getPredefinedCursor( 55 Cursor.WAIT_CURSOR ) ); Reading a File on a Web Server • setCursor( Cursor ) (inherited by JFrame) • Sets mouse cursor • static method getPredefinedCursor( int cursorType ) • Returns Cursor • cursorType • Cursor.WAIT_CURSOR • Cursor.DEFAULT_CURSOR

  14. 1 // Fig. 21.2: ReadServerFile.java 2 // This program uses a JEditorPane to display the 3 // contents of a file on a Web server. 4 import java.awt.*; 5 import java.awt.event.*; JFrame inherits setCursor method, which our class can now use. 6 import java.net.*; 7 import java.io.*; 8 import javax.swing.*; 9 import javax.swing.event.*; 10 11public class ReadServerFile extends JFrame { 12 private JTextField enter; 13 private JEditorPane contents; 14 15 public ReadServerFile() 16 { 17 super( "Simple Web Browser" ); 18 19 Container c = getContentPane(); 20 21 enter = new JTextField( "Enter file URL here" ); 22 enter.addActionListener( 23 new ActionListener() { 24 public void actionPerformed( ActionEvent e ) 25 { 26 getThePage( e.getActionCommand() ); 27 } 28 } 29 ); 1. import 1.1 extendsJFrame 1.2 Constructor

  15. 34 contents.addHyperlinkListener( Create JEditorPane, register event handler (HyperLinkEvents). 35 new HyperlinkListener() { 36 public void hyperlinkUpdate( HyperlinkEvent e ) Make sure user clicked hyperlink (ACTIVATED). 37 { 38 if ( e.getEventType() == Get the URL of hyperlink, call utility method getThePage. 39 HyperlinkEvent.EventType.ACTIVATED ) 40 getThePage( e.getURL().toString() ); 41 } Change cursor to a waiting state (downloading file). 42 } 43 ); Display new page in JEditorPane. 44 45 c.add( new JScrollPane( contents ), 46 BorderLayout.CENTER ); 47 48 setSize( 400, 300 ); 49 show(); 50 } 51 52 private void getThePage( String location ) 53 { 54 setCursor( Cursor.getPredefinedCursor( 55 Cursor.WAIT_CURSOR ) ); 56 57 try { 58 contents.setPage( location ); 59 enter.setText( location ); 60 } 30 c.add( enter, BorderLayout.NORTH ); 31 32 contents = new JEditorPane(); 33 contents.setEditable( false ); 7800 1.3 JEditorPane 1.4 addHyperLink Listener 2. Method getThePage 2.1 setCursor 2.2 setPage

  16. 67 68 setCursor( Cursor.getPredefinedCursor( 69 Cursor.DEFAULT_CURSOR ) ); 70 } 71 72 public static void main( String args[] ) 73 { 74 ReadServerFile app = new ReadServerFile(); 75 76 app.addWindowListener( 77 new WindowAdapter() { 78 public void windowClosing( WindowEvent e ) 79 { 80 System.exit( 0 ); 81 } 82 } 83 ); 84 } 85 } 61 catch ( IOException io ) { 62 JOptionPane.showMessageDialog( this, 63 "Error retrieving specified URL", 64 "Bad URL", 65 JOptionPane.ERROR_MESSAGE ); 66 } 3. main

  17. Program Output

  18. Program Output

  19. Establishing a Simple Server (Using Stream Sockets) • Creating a Java server • Create ServerSocket object ServerSocket s = new ServerSocket( port, queueLength ); • Register port number and set max number of waiting clients • Binds server to port, waits for clients • Server listens indefinitely (blocks) for clients Socket connection = s.accept() • Connections managed by Socket objects • Returns Socket when connection established

  20. Establishing a Simple Client (Using Stream Sockets) • Creating a Java server • Get I/O objects for communication • OutputStream - sends info to client • InputStream - gets info from client • Server's input stream is client's output stream, and vice versa • Use Socket object to get references to streams • connection.getInputStream() • connection.getOutputStream() • Methods write and read • Send individual bytes

  21. Establishing a Simple Client (Using Stream Sockets) • Creating a Java server • Chaining stream types (sending objects and data, not bytes) ObjectInputStream input = new ObjectInputStream( connection.getInputStream() ) • Processing phase • Server/client communicate using InputStream and OutputStream • Termination • Transmission complete • Method close (of Socket) connection.close() • Networking appears as sequential file I/O • Sockets simplify networking

  22. Establishing a Simple Client (Using Stream Sockets) • Creating a Java client • Create Socket to connect to server Socket connection = new Socket( serverAddress, port ) • If successful, returns Socket • Else throws subclass of IOException • Get stream objects • connection.getInputStream() • connection.getOutputStream() • Use chaining if transmitting objects and data, not pure bytes • ObjectInputStream, ObjectOutputStream

  23. Establishing a Simple Client (Using Stream Sockets) • Creating a Java client • Processing phase • Communicate using stream objects • Termination • Transmission complete • connection.close() (close Socket) • Client must determine when server done • read returns -1 when eof found • ObjectInputStream generates EOFException

  24. Client/Server Interaction with Stream Socket Connections • Upcoming program • Simple client/server chat application • Use stream sockets • Client connects, transmit String objects • do-while loop to get input • Event handler calls sendData method to send output • When either sends TERMINATE, connection terminates • Server waits for next client • GUI:

  25. 60 connection.getInetAddress().getHostName() ); 63 output = new ObjectOutputStream( 64 connection.getOutputStream() ); 65 output.flush(); Client/Server Interaction with Stream Socket Connections • Server • Once connection (Socket) established • getInetAddress() - returns InetAddress object • getHostName() - returns client's host name • Create ObjectOutputStream • flush() • Sends stream header to client • Required by client's ObjectInputStream

  26. 108 private void sendData( String s ) 109 { 111 output.writeObject( "SERVER>>> " + s ); 112 output.flush(); 113 display.append( "\nSERVER>>>" + s ); 81 display.setCaretPosition( 82 display.getText().length() ); Client/Server Interaction with Stream Socket Connections • Send/receive data • Method sendData called by event handler • Buffer flushed after every transmission • Sets cursor position to end of text • Allows JTextArea to scroll with text • Server processes single connection at a time • More likely to have separate threads for each connection

  27. 1 // Fig. 21.3: Server.java 2 // Set up a Server that will receive a connection 3 // from a client, send a string to the client, 4 // and close the connection. 5 import java.io.*; 6 import java.net.*; 7 import java.awt.*; 8 import java.awt.event.*; 9 import javax.swing.*; 10 11 public class Server extends JFrame { 12 private JTextField enter; 13 private JTextArea display; 14 ObjectOutputStream output; 15 ObjectInputStream input; 16 17 public Server() 18 { 19 super( "Server" ); 20 21 Container c = getContentPane(); 22 23 enter = new JTextField(); 24 enter.setEnabled( false ); 1. Constructor 1.1 GUI components

  28. 34 35 display = new JTextArea(); 36 c.add( new JScrollPane( display ), The event handlers calls method sendData, using text in JTextField as argument. 37 BorderLayout.CENTER ); 38 39 setSize( 300, 150 ); 40 show(); 41 } Register port 5000, server will allow 100 clients to wait in queue. 42 43 public void runServer() 44 { 45 ServerSocket server; 46 Socket connection; 47 int counter = 1; 48 49 try { 50 // Step 1: Create a ServerSocket. 51 server = new ServerSocket( 5000, 100 ); 52 25 enter.addActionListener( 26 new ActionListener() { 27 public void actionPerformed( ActionEvent e ) 28 { 29 sendData( e.getActionCommand() ); 30 } 31 } 32 ); 33 c.add( enter, BorderLayout.NORTH ); 1.2 Event handler 1.3 GUI 2. Method runServer 2.1 ServerSocket

  29. 67 connection.getInputStream() ); Infinite loop to wait for connections from clients. 68 display.append( "\nGot I/O streams\n" ); 69 Wait for connection (server.accept() waits indefinitely). 70 // Step 4: Process connection. 71 String message = Display host location. 72 "SERVER>>> Connection successful"; Set up I/O streams, flush buffer (sends stream data). Send confirmation message. 73 output.writeObject( message ); 74 output.flush(); Loop to get input. Set cursor to end of text. 75 enter.setEnabled( true ); 76 77 do { 78 try { 79 message = (String) input.readObject(); 80 display.append( "\n" + message ); 81 display.setCaretPosition( 82 display.getText().length() ); 83 } 53 while ( true ) { 54 // Step 2: Wait for a connection. 55 display.setText( "Waiting for connection\n" ); 56 connection = server.accept(); 57 58 display.append( "Connection " + counter + 59 " received from: " + 60 connection.getInetAddress().getHostName() ); 61 62 // Step 3: Get input and output streams. 63 output = new ObjectOutputStream( 64 connection.getOutputStream() ); 65 output.flush(); 66 input = new ObjectInputStream( 2.2 accept 2.3 getHostName 2.4 Get streams 2.5 writeObject 2.6 Loop

  30. 100 catch ( EOFException eof ) { Loop until TERMINATE string sent. 101 System.out.println( "Client terminated connection" ); 102 } 103 catch ( IOException io ) { Close connection and I/O streams. 104 io.printStackTrace(); 105 } 106 } 107 Send String object to client. Flush buffer to ensure it is sent, and update server's display. 108 private void sendData( String s ) 109 { 110 try { 111 output.writeObject( "SERVER>>> " + s ); 112 output.flush(); 113 display.append( "\nSERVER>>>" + s ); 114 } 84 catch ( ClassNotFoundException cnfex ) { 85 display.append( 86 "\nUnknown object type received" ); 87 } 88 } while ( !message.equals( "CLIENT>>> TERMINATE" ) ); 89 90 // Step 5: Close connection. 91 display.append( "\nUser terminated connection" ); 92 enter.setEnabled( false ); 93 output.close(); 94 input.close(); 95 connection.close(); 96 97 ++counter; 98 } 99 } 2.6 Loop 2.7 close 3. Method sendData 3.1 writeObject 3.2 flush

  31. 133 134 app.runServer(); 135 } 136 } 115 catch ( IOException cnfex ) { 116 display.append( 117 "\nError writing object" ); 118 } 119 } 120 121 public static void main( String args[] ) 122 { 123 Server app = new Server(); 124 125 app.addWindowListener( 126 new WindowAdapter() { 127 public void windowClosing( WindowEvent e ) 128 { 129 System.exit( 0 ); 130 } 131 } 132 ); 4. main

  32. Client/Server Interaction with Stream Socket Connections • Client • Similar to server • Creates same GUI • Loops to wait for input • Sends output through event handler and sendData

  33. 50 client = new Socket( 51 InetAddress.getByName( "127.0.0.1" ), 5000 ); Client/Server Interaction with Stream Socket Connections • Create Socket with two arguments • Internet address of server and port number • static method getByName (Class InetAddress) • Returns InetAddress object • Takes String • Could have taken "localhost" or called static method getLocalHost • Create I/O objects as before • Output of server is input of client

  34. 1 // Fig. 21.4: Client.java 2 // Set up a Client that will read information sent 3 // from a Server and display the information. 4 import java.io.*; 5 import java.net.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 import javax.swing.*; 9 10 public class Client extends JFrame { 11 private JTextField enter; 12 private JTextArea display; 13 ObjectOutputStream output; 14 ObjectInputStream input; 15 String message = ""; 16 17 public Client() 18 { 19 super( "Client" ); 20 21 Container c = getContentPane(); 22 23 enter = new JTextField(); 24 enter.setEnabled( false ); 1. Constructor 1.1 GUI

  35. 34 35 display = new JTextArea(); 36 c.add( new JScrollPane( display ), Client gets text from JTextField and calls sendData. 37 BorderLayout.CENTER ); 38 39 setSize( 300, 150 ); 40 show(); Create Socket to server, make connection. 41 } 42 43 public void runClient() 44 { 45 Socket client; 46 47 try { 48 // Step 1: Create a Socket to make connection. 49 display.setText( "Attempting connection\n" ); 50 client = new Socket( 51 InetAddress.getByName( "127.0.0.1" ), 5000 ); 52 53 54 55 25 enter.addActionListener( 26 new ActionListener() { 27 public void actionPerformed( ActionEvent e ) 28 { 29 sendData( e.getActionCommand() ); 30 } 31 } 32 ); 33 c.add( enter, BorderLayout.NORTH ); 1.2 Event handler 1.3 GUI 2. Method runClient 2.1 Socket

  36. 67 // Step 3: Process connection. 68 enter.setEnabled( true ); 69 70 do { 71 try { Code similar to server. Create I/O objects, flush buffer, loop to wait for and process input. 72 message = (String) input.readObject(); 73 display.append( "\n" + message ); 74 display.setCaretPosition( 75 display.getText().length() ); 76 } 77 catch ( ClassNotFoundException cnfex ) { 78 display.append( 79 "\nUnknown object type received" ); 80 } 81 } while ( !message.equals( "SERVER>>> TERMINATE" ) ); 82 56 display.append( "Connected to: " + 57 client.getInetAddress().getHostName() ); 58 59 // Step 2: Get the input and output streams. 60 output = new ObjectOutputStream( 61 client.getOutputStream() ); 62 output.flush(); 63 input = new ObjectInputStream( 64 client.getInputStream() ); 65 display.append( "\nGot I/O streams\n" ); 66 2.2 I/O streams 2.3 flush 2.4 Loop

  37. 100 message = s; 101 output.writeObject( "CLIENT>>> " + s ); 102 output.flush(); 103 display.append( "\nCLIENT>>>" + s ); 104 } 105 catch ( IOException cnfex ) { 106 display.append( 107 "\nError writing object" ); 108 } 109 } 110 83 // Step 4: Close connection. 84 display.append( "Closing connection.\n" ); 85 input.close(); 86 output.close(); 87 client.close(); 88 } 89 catch ( EOFException eof ) { 90 System.out.println( "Server terminated connection" ); 91 } 92 catch ( IOException e ) { 93 e.printStackTrace(); 94 } 95 } 96 97 private void sendData( String s ) 98 { 99 try { 2.5 close 3. Method sendData

  38. 111 public static void main( String args[] ) 112 { 113 Client app = new Client(); 114 115 app.addWindowListener( 116 new WindowAdapter() { 117 public void windowClosing( WindowEvent e ) 118 { 119 System.exit( 0 ); 120 } 121 } 122 ); 123 124 app.runClient(); 125 } 126 } 127 4. main Program Output

  39. Program Output

  40. Connectionless Client/Server Interaction with Datagrams • Connection-oriented interaction • Like phone call • Have connection to other end • Connection maintained for duration of call, even if not talking • Connectionless interaction • Like sending postal mail • Use datagrams, packets of data • If large packet, break into smaller pieces • Send separately • May arrive out of order or not arrive at all • Duplicates may arrive

  41. 40 byte data[] = new byte[ 100 ]; 41 receivePacket = 42 new DatagramPacket( data, data.length ); 45 socket.receive( receivePacket ); 27 socket = new DatagramSocket( 5000 ); Connectionless Client/Server Interaction with Datagrams • DatagramSocket( port ) • Binds server to port • DatagramPacket( byteArray, byteArray.length ) • Create DatagramPacket to store received packet • byteArray stores data • Method receive( packetToStore ) • Blocks until packet arrives, stores in packetToStore

  42. 48 display.append( "\nPacket received:" + 49 "\nFrom host: " + receivePacket.getAddress() + 50 "\nHost port: " + receivePacket.getPort() + 51 "\nLength: " + receivePacket.getLength() + 52 "\nContaining:\n\t" + 53 new String( receivePacket.getData(), 0, 54 receivePacket.getLength() ) ); Connectionless Client/Server Interaction with Datagrams • getAddress - returns InetAddress • getPort, getLength - return integers • getData - returns byte array • Used in String constructor to create string

  43. 58 sendPacket = 59 new DatagramPacket( receivePacket.getData(), 60 receivePacket.getLength(), 61 receivePacket.getAddress(), 62 receivePacket.getPort() ); 63 socket.send( sendPacket ); Connectionless Client/Server Interaction with Datagrams • Echo packet back to client • DatagramPacket( byteArray, length, InetAddress, port ) • Method send( packetToSend )

  44. 1 // Fig. 21.5: Server.java 2 // Set up a Server that will receive packets from a 3 // client and send packets to a client. 4 import java.io.*; 5 import java.net.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 import javax.swing.*; 9 Create new DatagramSocket, binds server to port. 10 public class Server extends JFrame { 11 private JTextArea display; 12 13 private DatagramPacket sendPacket, receivePacket; 14 private DatagramSocket socket; 15 16 public Server() 17 { 18 super( "Server" ); 19 20 display = new JTextArea(); 21 getContentPane().add( new JScrollPane( display), 22 BorderLayout.CENTER ); 23 setSize( 400, 300 ); 24 show(); 25 26 try { 27 socket = new DatagramSocket( 5000 ); 28 } 1. Declarations 1.1 DatagramSocket

  45. 34 35 public void waitForPackets() Loop to wait for packets. 36 { Create new DatagramPacket to receive info. 37 while ( true ) { 38 try { 39 // set up packet 40 byte data[] = new byte[ 100 ]; Gather and display packet data. Convert byte array to a String. 41 receivePacket = 42 new DatagramPacket( data, data.length ); 43 Create packet back to client. 44 // wait for packet 45 socket.receive( receivePacket ); 46 47 // process packet 48 display.append( "\nPacket received:" + 49 "\nFrom host: " + receivePacket.getAddress() + 50 "\nHost port: " + receivePacket.getPort() + 51 "\nLength: " + receivePacket.getLength() + 52 "\nContaining:\n\t" + 53 new String( receivePacket.getData(), 0, 54 receivePacket.getLength() ) ); 55 56 // echo information from packet back to client 57 display.append( "\n\nEcho data to client..."); 58 sendPacket = 59 new DatagramPacket( receivePacket.getData(), 29 catch( SocketException se ) { 30 se.printStackTrace(); 31 System.exit( 1 ); 32 } 33 } 2. Method waitForPackets 2.1 receivePacket 2.2 receive 2.3 Process packet 2.4 Echo packet

  46. 67 } 68 catch( IOException io ) { Send packet back to client. 69 display.append( io.toString() + "\n" ); 70 io.printStackTrace(); 71 } 72 } 73 } 74 75 public static void main( String args[] ) 76 { 77 Server app = new Server(); 78 79 app.addWindowListener( 80 new WindowAdapter() { 81 public void windowClosing( WindowEvent e ) 82 { 83 System.exit( 0 ); 84 } 85 } 86 ); 87 88 app.waitForPackets(); 89 } 90 } 60 receivePacket.getLength(), 61 receivePacket.getAddress(), 62 receivePacket.getPort() ); 63 socket.send( sendPacket ); 64 display.append( "Packet sent\n" ); 65 display.setCaretPosition( 66 display.getText().length() ); 2.5 send 3. main

  47. Program Output

  48. 31 socket = new DatagramSocket(); Connectionless Client/Server Interaction with Datagrams • Client • Similar to server • Has JTextField • Sends packets with event handler for JTextField • Convert String to byteArray • String.getBytes() • Have loop to receive echoed packets from server • Constructor needs no arguments • Uses next available port • Server gets client's port number as part of DatagramPacket

  49. 1 // Fig. 21.6: Client.java 2 // Set up a Client that will send packets to a 3 // server and receive packets from a server. 4 import java.io.*; 5 import java.net.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 import javax.swing.*; 9 10 public class Client extends JFrame implements ActionListener { 11 private JTextField enter; 12 private JTextArea display; 13 14 private DatagramPacket sendPacket, receivePacket; 15 private DatagramSocket socket; 16 17 public Client() 18 { 19 super( "Client" ); 20 21 enter = new JTextField( "Type message here" ); 22 enter.addActionListener( this ); 23 getContentPane().add( enter, BorderLayout.NORTH ); 24 display = new JTextArea(); 25 getContentPane().add( new JScrollPane( display ), 26 BorderLayout.CENTER ); 27 setSize( 400, 300 ); 28 show(); 29 1. Constructor 1.1 GUI 1.2 Register event handler

More Related