Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.

Similar presentations

Presentation on theme: "1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast."— Presentation transcript:

1 1 Networking with Java 2: The Server Side

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 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 This definition is not always intuitive: X servers.

4 4 Client-Server Interaction

5 5

6 6

7 7

8 8

9 9 Java Server Sockets

10 10 Java Sockets – A Reminder Java wraps OS sockets (over TCP) by the objects of class 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 11 Java ServerSocket 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 for the new channel -blocks until connection is made Read more about ServerSocket ClassServerSocket Class 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.

12 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 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(); } run the example bytes chars

14 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. (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.) We will discuss threads later today.

15 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, is thrown

16 16 Socket socket = new Socket("", 80); InputStream istream = socket.getInputStream(); OutputStream ostream = socket.getOutputStream(); String request = "GET /~dbi/admin.html HTTP/1.1\r\n" + "Host:\r\n" + "Connection: close\r\n\r\n"; ostream.write(request.getBytes()); byte[] response = new byte[4096]; int bytesRead = -1; while ((bytesRead = >= 0) { System.out.write(response, 0, bytesRead); } socket.close(); SimpleSocket – A Reminder

17 17 Get Vs. Post Get -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 18 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((>=0) { System.out.write(data,0,bytesRead); }}} ContentExtractor – A Reminder

19 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 20 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 = >= 0) System.out.write(response, 0, bytesRead); in.close(); POST Example - SearchWalla

21 21 POST / HTTP/1.1 User-Agent: Java/1.5.0_01 Host: 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 "Java networking" Sent Headers

22 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.proxyPort=8080... Another option is to set the environment variables in the program itself System.getProperties().put( “http.proxyHost", "" ); System.getProperties().put( “http.proxyPort", "8080" ); Read more about networking with proxiesnetworking with proxies

23 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 "1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast."

Similar presentations

Ads by Google