Presentation is loading. Please wait.

Presentation is loading. Please wait.

Networking with Java 2.

Similar presentations


Presentation on theme: "Networking with Java 2."— Presentation transcript:

1 Networking with Java 2

2 Some Terms Mentioned Last Week
TCP Relatively slow but enables reliable byte-stream transmission UDP Fast unreliable datagram (packet) transmission Ports Application’s “channel address” Sockets Endpoint representation of 2-way communication channel between programs

3 Client-Server Model A common paradigm for distributed applications
Asymmetry in connection establishment: Server waits for client requests (daemon) at a well known address (IP+port) Connection is established upon client request Once the connection is made, it can be either symmetric (TELNET) or asymmetric (HTTP) For example: Web servers and browsers

4 Client-Server Interaction

5 Client-Server Interaction

6 Client-Server Interaction

7 Client-Server Interaction

8 Client-Server Interaction

9 Java Sever Sockets

10 Java Sockets – A Reminder
Java wraps OS sockets (over TCP) by the objects of class java.net.Socket new Socket(String remoteHost, int remotePort) creates a TCP socket and connects it to the remote host on the remote port (hand shake) Write and read using streams: InputStream getInputStream() OutputStream getOutputStream()

11 Java ServerSocket Construction: Listen and accept incoming connections
ServerSocket represents a socket that listens and waits for requests from clients Construction: new ServerSocket(int port) Why do we want to specify the port? Listen and accept incoming connections Socket accept() returns a new socket (with a new port) for the new channel blocks until connection is made Read more about ServerSocket Class

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("Hello " + clientName + "!"); writer.flush(); String lineRead = null; while ((lineRead = reader.readLine()) != null) { writer.println("You wrote: " + lineRead); writer.flush(); } chars bytes run the example

14 Accepting Connections
Usually, the accept() method is executed within an infinite loop i.e., while(true){...} Whenever accept() returns, a new thread is launched to handle that interaction (not in our example) Hence, the server can handle several requests concurrently

15 Timeout You can set timeout values to the blocking method
accept() of ServerSocket Use the method serverSocket.setSoTimeout(milliseconds) If timeout is reached before the method returns, java.net.SocketTimeoutException is thrown

16 SimpleSocket – A Reminder
 Socket socket = new Socket("     InputStream istream = socket.getInputStream();     OutputStream ostream = socket.getOutputStream();     String request =        "GET /~dbi/admin.html HTTP/1.1\r\n"  +        "Host:        "Connection: close\r\n\r\n";             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 Get Post Returns the content of the requested URL
Usually a static resource Post A block of data is sent with the request Usually a program or a form

18 ContentExtractor – A Reminder
public class ContentExtractor {   public static void main(String[] argv) throws Exception {     URL url = new URL(argv[0]);                System.out.println("Host: " + url.getHost());     System.out.println("Protocol: " + url.getProtocol());     System.out.println("----");     HttpURLConnection 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 In order to send POST requests with HttpURLConnection, you have to do the following: Enable connection output: con.setDoOutput(true); Get the output stream: con.getOutputStream() This changes the method from GET to POST Write the message body into the output stream close the output stream (important!)

20 POST Example - SearchWalla
URL url = new URL(" URLConnection connection = url.openConnection(); connection.setDoOutput(true); String query = "q=" + URLEncoder.encode(argv[0], "UTF-8");      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 java SearchWalla "Java networking"
Sent Headers java SearchWalla "Java networking" 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

22 Defining Default Proxy
For reading a URL using a proxy, we run java with the environment variables for http.proxyHost and http.proxyPort set properly: java –Dhttp.proxyHost=wwwproxy.huji.ac.il –Dhttp.proxyPort= Another option is to set the environment variables in the program itself System.getProperties().put( “http.proxyHost", "wwwproxy.huji.ac.il" ); System.getProperties().put( “http.proxyPort", "8080" ); Read more about networking with proxies

23 Not Covered: UDP Connections
The URL, URLConnection, Socket and ServerSocket classes all use the TCP protocol to communicate over the network Java programs can also use UDP protocol for communication For that, use DatagramPacket, DatagramSocket, and MulticastSocket classes


Download ppt "Networking with Java 2."

Similar presentations


Ads by Google