1 networking with java 2: the server side. 2 some terms mentioned last week tcp -relatively slow but...

23
1 Networking Networking with Java 2: with Java 2: The Server The Server Side Side

Post on 20-Dec-2015

213 views

Category:

Documents


1 download

TRANSCRIPT

1

Networking with Networking with Java 2:Java 2:

The Server SideThe Server Side

2

Some Terms Mentioned Last WeekSome 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 ModelClient-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

Client-Server InteractionClient-Server Interaction

Client

Server

80

Client

5

Client-Server InteractionClient-Server Interaction

Client

Server

80

Client

6945

6

Client-Server InteractionClient-Server Interaction

Client

Server

80

Client

1932

6945

7

Client-Server InteractionClient-Server Interaction

Client

Server

80

Client

1932

6945

8002

8

Client-Server InteractionClient-Server Interaction

Client

Server

80

Client

1932

6945

8002

2341

9

Java Server SocketsJava Server Sockets

10

Java Sockets – A ReminderJava 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 Java ServerSocketServerSocket• 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 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

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(); }

run the example

bytes

chars

14

Accepting ConnectionsAccepting 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

TimeoutTimeout

• 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

 Socket socket = new Socket("www.cs.huji.ac.il", 80);    InputStream istream = socket.getInputStream();    OutputStream ostream = socket.getOutputStream();

    String request =       "GET /~dbi/admin.html HTTP/1.1\r\n"  +       "Host: www.cs.huji.ac.il\r\n" +       "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();

SimpleSocket – A ReminderSimpleSocket – A Reminder

17

Get Vs. PostGet 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

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);}}}

ContentExtractor – A ReminderContentExtractor – A Reminder

19

Sending POST RequestsSending 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

URL url = new URL("http://find.walla.co.il/");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();

POST Example - SearchWallaPOST Example - SearchWalla

21

POST / HTTP/1.1User-Agent: Java/1.5.0_01Host: find.walla.co.ilAccept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2Connection: keep-aliveContent-type: application/x-www-form-urlencodedContent-Length: 18

q=Java+networking

java SearchWalla "Java networking"

Sent HeadersSent Headers

22

Defining Default ProxyDefining 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=8080 ...

• Another option is to set the environment variables in the

program itselfSystem.getProperties().put( “http.proxyHost", "wwwproxy.huji.ac.il" );

System.getProperties().put( “http.proxyPort", "8080" );

Read more about networking with proxies

23

Not Covered: UDP ConnectionsNot 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.