Download presentation
Presentation is loading. Please wait.
Published byMariah Cunningham Modified over 9 years ago
1
Lab2: Socket Programming Lecturer: Mauro Conti T.A.: Eyüp S. Canlar
2
Exercise 1 Write a client and a multi-threaded server program Clients send a message to the server Usage: java Lab2Client Server prints the message out Usage: java Lab2Server
3
Exercise 1: client and server //Client code Socket socket = new Socket(“localhost”, 12345); //Send message …. //Server code ServerSocket servSocket = new ServerSocket(12345); while(true){ Socket cliSocket = servSocket.accept(); //Create a thread to handle //client print request }
4
Exercise 2 Write a program HttpGet.java Usage: java HttpGet Requirements: int start(String[] argv) Initialize Socket, BufferedReader, and BufferedWriter void sendGetRequest(String filename, BufferedWriter out) throws IOException Send GET request: “GET /path/index.html HTML/1.0\r\n\r\n” void receiveGetResponse(BufferedReader in) throws IOException Reads the response and prints it line by line on standard output
5
Exercise 2: start(String[] argv) public void start(String[] argv){ try{ Socket socket = new Socket(argv[0]); BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); BufferedWriter out = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream()); …. } catch(Exception e){….} }
6
Exercise 2: send and receive Sending GET request out.write(getRequest); out.flush(); Receiving reply from web server while (line = in.readln() != null){….}
7
Exercise 3 Modify the program of Exercise 1 to store the received file. To achieve this: Write a method to parse the path to distil the filename Send GET request and receive reply Skip the header of the reply and store the remainder in the local file
8
Exercise 3: parsing the path StringTokenizer strtok = new StringTokenizer(path, “/”); //skip all the tokens until the last one …. filename = strtok.nextToken();
9
Exercise 3: parsing reply while(/*some condition*/){ line = in.readLine(); if(line=“” && !firstEmptyLine){ //We reached the end of the header } if(firstEmptyLine){ //Start reading payload }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.