9
Lab2: Socket Programming Lecturer: Mauro Conti T.A.: Eyüp S. Canlar

Lab2: Socket Programming

Embed Size (px)

DESCRIPTION

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 Server prints the message out Usage: java Lab2Server. //Client code - PowerPoint PPT Presentation

Citation preview

Page 1: Lab2: Socket Programming

Lab2: Socket Programming

Lecturer: Mauro Conti

T.A.: Eyüp S. Canlar

Page 2: Lab2: Socket Programming

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

Page 3: Lab2: Socket Programming

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

}

Page 4: Lab2: Socket Programming

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

Page 5: Lab2: Socket Programming

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){….}

}

Page 6: Lab2: Socket Programming

Exercise 2: send and receive

Sending GET request out.write(getRequest); out.flush();

Receiving reply from web server while (line = in.readln() != null){….}

Page 7: Lab2: Socket Programming

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

Page 8: Lab2: Socket Programming

Exercise 3: parsing the path

StringTokenizer strtok = new StringTokenizer(path, “/”);

//skip all the tokens until the last one

….

filename = strtok.nextToken();

Page 9: Lab2: Socket Programming

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 }

}