Transcript ppt

Networking with
Java 2:
The Server Side
1
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
2
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.
3
Client-Server Interaction
Client
80
Server
Client
4
Client-Server Interaction
6945
Client
80
Server
Client
5
Client-Server Interaction
6945
1932
Client
80
Server
Client
6
Client-Server Interaction
6945
1932
Client
80
Server
8002
Client
7
Client-Server Interaction
6945
1932
Client
80
2341
Server
8002
Client
8
Java Server Sockets
9
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()
10
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
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.
- blocks until connection is made
Read more about ServerSocket Class
11
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) {} }
}}}
12
socket = serverSocket.accept();
String clientName = socket.getInetAddress().getHostName();
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
chars
PrintStream writer = new
bytes
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
13
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.
14
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
15
SimpleSocket – A Reminder
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();
16
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
17
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);
}}}
18
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!)
19
POST Example - SearchWalla
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();
20
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
21
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=8080 ...
• 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
22
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.
23