Your SlideShare is downloading. ×
0
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
ppt
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

ppt

1,381

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,381
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
44
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Networking with Java 2: The Server Side
  • 2. Some Terms Mentioned Last Week <ul><li>TCP </li></ul><ul><ul><li>Relatively slow but enables reliable byte-stream transmission </li></ul></ul><ul><li>UDP </li></ul><ul><ul><li>Fast unreliable datagram (packet) transmission </li></ul></ul><ul><li>Ports </li></ul><ul><ul><li>Application’s “channel address” </li></ul></ul><ul><li>Sockets </li></ul><ul><ul><li>Endpoint representation of 2-way communication channel between programs </li></ul></ul>
  • 3. Client-Server Model <ul><li>A common paradigm for distributed applications </li></ul><ul><li>Asymmetry in connection establishment: </li></ul><ul><ul><li>Server waits for client requests (daemon) at a well known address (IP+port) </li></ul></ul><ul><ul><li>Connection is established upon client request </li></ul></ul><ul><li>Once the connection is made, it can be either symmetric (TELNET) or asymmetric (HTTP) </li></ul><ul><li>For example: Web servers and browsers </li></ul><ul><li>This definition is not always intuitive: X servers. </li></ul>
  • 4. Client-Server Interaction
  • 5. Client-Server Interaction
  • 6. Client-Server Interaction
  • 7. Client-Server Interaction
  • 8. Client-Server Interaction
  • 9. Java Server Sockets
  • 10. Java Sockets – A Reminder <ul><li>Java wraps OS sockets (over TCP) by the objects of class java.net.Socket </li></ul><ul><li>new Socket (String remoteHost , int remotePort ) creates a TCP socket and connects it to the remote host on the remote port (hand shake) </li></ul><ul><li>Write and read using streams: </li></ul><ul><ul><li>InputStream getInputStream() </li></ul></ul><ul><ul><li>OutputStream getOutputStream() </li></ul></ul>
  • 11. Java ServerSocket <ul><li>ServerSocket represents a socket that listens and waits for requests from clients </li></ul><ul><li>Construction: </li></ul><ul><ul><li>new ServerSocket(int port) </li></ul></ul><ul><ul><li>Why do we want to specify the port? </li></ul></ul><ul><li>Listen and accept incoming connections </li></ul><ul><ul><li>Socket accept() </li></ul></ul><ul><ul><li>returns a new socket for the new channel </li></ul></ul><ul><ul><li>blocks until connection is made </li></ul></ul>Read more about ServerSocket Class <ul><ul><li>Not that it matters for you, but avoid a common mistake: the new socket is not bound to a new port but to the same port. </li></ul></ul>
  • 12. public class EchoServer { public static void main ( String [] args ) throws IOException { ServerSocket serverSocket = new ServerSocket ( 8000 ) ; Socket socket = null ; while ( true ) { try { ... next slide ... } catch ( IOException exp ) { ... } finally { try { if ( !socket.isClosed ()) socket.close () ; } catch ( IOException e ) {} } }}}
  • 13. socket = serverSocket.accept () ; String clientName = socket.getInetAddress () .getHostName () ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( socket.getInputStream ())) ; PrintStream writer = new PrintStream ( socket.getOutputStream ()) ; writer.println ( &quot;Hello &quot; + clientName + &quot;!&quot; ) ; writer.flush () ; String lineRead = null ; while (( lineRead = reader.readLine ()) != null ) { writer.println ( &quot;You wrote: &quot; + lineRead ) ; writer.flush () ; } run the example bytes chars
  • 14. Accepting Connections <ul><li>Usually, the accept() method is executed within an infinite loop </li></ul><ul><ul><li>i.e., while(true) {...} </li></ul></ul><ul><li>Whenever accept() returns, a new thread is launched to handle that interaction (not in our example). </li></ul><ul><li>Hence, the server can handle several requests concurrently. (Note that you could also manage the work/time spent on each socket on your own – this is useful if the thread limit of the OS or the thread swap time is your bottleneck. This (almost) never happens.) </li></ul><ul><li>We will discuss threads later today. </li></ul>
  • 15. Timeout <ul><li>You can set timeout values to the blocking method accept() of ServerSocket </li></ul><ul><li>Use the method serverSocket. setSoTimeout (milliseconds) </li></ul><ul><li>If timeout is reached before the method returns, java.net. SocketTimeoutException is thrown </li></ul>
  • 16. SimpleSocket – A Reminder   Socket socket =  new  Socket ( &quot;www.cs.huji.ac.il&quot; ,  80 ) ;      InputStream istream = socket.getInputStream () ;      OutputStream ostream = socket.getOutputStream () ;      String request =         &quot;GET /~dbi/admin.html HTTP/1.1 &quot;   +         &quot;Host: www.cs.huji.ac.il &quot;  +         &quot;Connection: close &quot; ;               ostream.write ( request.getBytes ()) ;      byte []  response =  new byte [ 4096 ] ; int  bytesRead = - 1 ;        while  (( bytesRead = istream.read ( response ))  >=  0 ) {        System.out.write ( response,  0 , bytesRead ) ;      }      socket.close () ;
  • 17. Get Vs. Post <ul><li>Get </li></ul><ul><ul><li>Returns the content of the requested URL </li></ul></ul><ul><ul><li>Usually a static resource </li></ul></ul><ul><li>Post </li></ul><ul><ul><li>A block of data is sent with the request </li></ul></ul><ul><ul><li>Usually a program or a form </li></ul></ul>
  • 18. ContentExtractor – A Reminder public class  ContentExtractor  {    public static void  main ( String []  argv )  throws  Exception  {      URL url =  new  URL ( argv [ 0 ]) ;                System.out.println ( &quot;Host: &quot;  + url.getHost ()) ;      System.out.println ( &quot;Protocol: &quot;  + url.getProtocol ()) ;      System.out.println ( &quot;----&quot; ) ;      Http URLConnection con = url.openConnection () ;      InputStream stream = con.getInputStream () ;               byte []  data =  new byte [ 4096 ] ;   int  bytesRead =  0 ;       while (( bytesRead=stream.read ( data )) >= 0 ) {         System.out.write ( data, 0 ,bytesRead ) ; }}}
  • 19. Sending POST Requests <ul><li>In order to send POST requests with HttpURLConnection , you have to do the following: </li></ul><ul><ul><li>Enable connection output: con.setDoOutput(true); </li></ul></ul><ul><ul><li>Get the output stream: con.getOutputStream() </li></ul></ul><ul><ul><ul><li>This changes the method from GET to POST </li></ul></ul></ul><ul><ul><li>Write the message body into the output stream </li></ul></ul><ul><ul><li>close the output stream (important!) </li></ul></ul>
  • 20. POST Example - SearchWalla URL url =  new  URL ( &quot;http://find.walla.co.il/&quot; ) ; URLConnection connection = url.openConnection () ; connection.setDoOutput ( true ) ; String query =  &quot;q=&quot;  + URLEncoder.encode ( argv [ 0 ] ,  &quot;UTF-8&quot; ) ;      OutputStream out = connection.getOutputStream () ;   out.write ( query.getBytes ()) ; out.close () ; InputStream in = connection.getInputStream () ; int  bytesRead = - 1 ;   byte []  response =  new byte [ 4096 ] ; while  (( bytesRead = in.read ( response ))  >=  0 )        System.out.write ( response,  0 , bytesRead ) ; in.close () ;
  • 21. Sent Headers POST / HTTP/1.1 User-Agent: Java/1.5.0_01 Host: find.walla.co.il Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Connection: keep-alive Content-type: application/x-www-form-urlencoded Content-Length: 18 q=Java+networking java SearchWalla &quot;Java networking&quot;
  • 22. Defining Default Proxy <ul><li>For reading a URL using a proxy, we run java with the environment variables for http.proxyHost and http.proxyPort set properly: </li></ul><ul><ul><li>java –Dhttp.proxyHost= wwwproxy.huji.ac.il –Dhttp.proxyPort= 8080 ... </li></ul></ul><ul><li>Another option is to set the environment variables in the program itself </li></ul><ul><li>System.getProperties().put( “http.proxyHost&quot;, &quot; wwwproxy.huji.ac.il &quot; ); System.getProperties().put( “http.proxyPort&quot;, &quot; 8080 &quot; ); </li></ul>Read more about networking with proxies
  • 23. Not Covered: UDP Connections <ul><li>The URL , URLConnection , Socket and ServerSocket classes all use the TCP protocol to communicate over the network </li></ul><ul><li>Java programs can also use UDP protocol for communication </li></ul><ul><li>For that, use DatagramPacket , DatagramSocket , and MulticastSocket classes. </li></ul>

×