90 likes | 215 Views
Lab2: Socket Programming. Lecturer: Mauro Conti T.A.: Ey ü p S. Canlar. Exercise 1. Write a client and a multi-threaded server program Clients send a message to the server Usage: java Lab2Client <message> Server prints the message out Usage: java Lab2Server. //Client code
E N D
Lab2: Socket Programming Lecturer: Mauro Conti T.A.: Eyüp S. Canlar
Exercise 1 • Write a client and a multi-threaded server program • Clients send a message to the server • Usage: java Lab2Client <message> • Server prints the message out • Usage: java Lab2Server
//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 } Exercise 1: client and server
Exercise 2 • Write a program HttpGet.java • Usage: java HttpGet <host> <path> • 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
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){….} }
Exercise 2: send and receive • Sending GET request • out.write(getRequest); out.flush(); • Receiving reply from web server • while (line = in.readln() != null){….}
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
Exercise 3: parsing the path StringTokenizer strtok = new StringTokenizer(path, “/”); //skip all the tokens until the last one …. filename = strtok.nextToken();
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 } }