Created
May 9, 2011 17:44
-
-
Save jesjos/962952 to your computer and use it in GitHub Desktop.
Webber fetches webpages and displays character-counts or error-messages.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Question 5. | |
| Timeouten beräknas på basis av tre faktorer: rtt på nuvarande sample, en estimerad rtt som bygger på ett viktat medelvärde av rtt på tidigare samples samt en koefficient vid namn DevRTT som uttrycker hur stor variationen är. | |
| Vi vill att timeouten ska vara stor nog för att tillåta att paket fördröjs lite, men liten nog så att vi märker när paket har gått förlorade. Vi vill dessutom ha längre timeout när rtt-tiderna fluktuerar, samt kortare när de är mer stabila. Detta får vi genom att uttrycka timeout som den estimerade rtt:n plus fyra gånger variansvärdet. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.*; | |
| import java.net.*; | |
| class Webber { | |
| public Webber() { | |
| } | |
| public static String get(String url) { | |
| Socket s = null; | |
| String response = ""; | |
| // Input url can contain page URI, need to split to get host name | |
| String[] splitUrl = url.split("/", 2); | |
| String host = splitUrl[0]; | |
| String page = "/"; | |
| // By default, we fetch root (/), but if a page address is present we use it instead | |
| if (splitUrl.length > 1) page = "/" + splitUrl[1]; | |
| // Establish a socket | |
| try { | |
| s = new Socket(host, 80); | |
| } catch (Exception e) { | |
| return "Failed to establish socket: " + e.getMessage(); | |
| } | |
| try { | |
| DataOutputStream output = new DataOutputStream(s.getOutputStream()); | |
| BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); | |
| String request = "GET " + page + " HTTP/1.0\r\n\r\n"; | |
| // Send the request and get the first line | |
| output.writeBytes(request); | |
| response = input.readLine(); | |
| String code = response.split(" ")[1]; | |
| // We treat response codes below 300 as successes and return errors for all others | |
| if (Integer.valueOf(code) < 300) { | |
| while(input.ready()) { | |
| response += input.readLine(); | |
| } | |
| return "Received " + response.length() + " characters."; | |
| } else { | |
| return "Error: " + response; | |
| } | |
| } catch (Exception e) { | |
| // Sloppy code goes here | |
| } | |
| return response; | |
| } | |
| public static void main(String[] args) { | |
| System.out.println(Webber.get(args[0])); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment