Clients and ServersURL reviewHTTP reviewUsing a URLSocket reviewHow to write a serverHow to write a clientHow to write an HTTP serverProxy serversMultithreadingSynchronizationA synchronization analogyThe EndJan 14, 2019Clients and Servers2URL reviewA URL has the syntax:protocol://hostname:port/path#anchorimport java.net.*;This is the package that defines sockets, URLs, etc.URL url = new URL(String);Constructs a URL object from a text stringMalformedURLExceptionThis exception is thrown if the given String cannot be parsed by newURL(String)We have used URLs to display a page in an applet:appletContext.showUrl(URL)3HTTP reviewHTTP is a protocol--a formal description of a language that computers use to communicateAn HTTP message consists of three parts:–The request or the response line–A request line typically contains either GET or PUT–A response line contains the status code, such as 404 Not Found–A header section–Contains name-value pairs, such as Content-type: text/html–Ends with a blank line–The body of the message–The body is optional4Using a URLURLConnection c = url.openConnection(); The URLConnection is the basic way to access the resource informationc.getHeaderField(name)Returns the value of the named header field (as a String)Frequently used fields have shorthand methods, for example,c.getLastModified() = c.getHeaderField("last-modified")getHeaderField(int)Returns the value of the int-th header field (as a String)The 0-th header field is the status linec.getInputStream()Returns an InputStream containing the “content” of the resourceurl.openStream() is shorthand for url.openConnection().getInputStream()5Socket reviewA socket is a low-level software device for connecting two programs (possibly on different computers) togethernew Socket(String host, int port) Creates a client socket and makes the connectionMethods include getInputStream(), getOutputStream(), and close()new ServerSocket(int port)Creates a server socket that listens on the specified portaccept() returns a Socket that can be used for I/Oaccept() is a blocking method, so multithreading is highly desirable6How to write a serverServerSocket server = new ServerSocket(port)The port should be a number above 1024Socket client = server.accept();accept() blocks while it waits for a connectionInputStream inStream = client.getInputStream();InputStreamReader reader = new InputStreamReader(inStream);BufferedReader input = new BufferedReader(reader);char ch = input.read(), String s = input.readLine()OutputStream outStream = client.getOutputStream();PrintWriter output = new PrintWriter(outStream, true);true is so that you auto-flush, that is, don’t fill the bufferoutput .print(X), output .println(X), output .println()input.close(), output.close(), server.close(), client.close()7How to write a clientSocket server = new Socket(ip_address, port)The ip_address can be the String "localhost"This method makes the actual connectionInputStream inStream = server.getInputStream();As on the previous slideOutputStream outStream = server.getOutputStream();As on the previous slideinput.close(), output.close(), server.close()As on the previous slide8How to write an HTTP serverAn HTTP server is just a server that follows the HTTP protocol (request/status line, header, blank line, body)Since HTTP is a text-based protocol, compliance is easyThere are two versions of HTTP: 1.0 and 1.1HTTP 1.0 is simpler and should be used if the special features of 1.1 are not requiredThe most important change in HTTP 1.1 is that it can accommodate proxy serversThe client and server must agree which version of HTTP is being usedMost HTTP servers can use both9Proxy serversProxies are important because they allow more than one server to use the same IP addressThere aren’t enough IP addresses to go aroundIf you have a lot of clients, you need a lot of servers--but the user should not have to try multiple IP addressesclientclientclientserverhas IP addressWithout a proxyclientclientclientproxyhas IP addressserverserverWith a proxyclientclient10Multithreadingserver.accept() is a blocking call--Java stops and waits for a response before it continuesThis is only acceptable if the server never has more than one clientA server needs to have a separate thread for each clientThere are two ways to create a Thread:Write a class that extends ThreadOverride the public void run() methodCreate an instance of your class and call its (inherited) start() methodWrite a class that implements RunnableImplement the public void run() methodCreate an instance of your classCreate a Thread object with this instance as a parameter to the constructorCall the Thread object’s start() method11SynchronizationWhile an object is being modified by one thread, no other thread should try to access itThis leads to unpredictable (and difficult to debug) resultsYou can synchronize an object:synchronized (obj) { code that uses/modifies obj }synchronized is a statement type, like if or whileNo other code that is synchronized on this object can use or modify the object at the same timeYou can synchronize a method:synchronized void addOne(arg1, arg2, ...) { code }synchronized is a method modifier, like public or abstractOnly one synchronized method in a class can be used at a time (but this doesn’t restrict other, non-synchronized methods)Synchronization can really hurt efficiency (and response time)It can be very difficult to make a program both safe and efficient12A synchronization analogyImagine that you have a building with two entrancesOne entrance is always kept locked, and has a single keyThe other entrance is never lockedSynchronization is like thisCode that always uses the locked (synchronized) entrance has to wait for other code to exit and hand over the keyAny code that uses the unlocked entrance can go into the building at any time, regardless of what other code may be thereThus, synchronizing code only protects you from other synchronized code!13The
View Full Document