📄 modifiedclient.java
字号:
import java.io.*;
import java.net.*;
/**
* A client program which can send a request to server
* @author yaoyiyang
*
*/
public class ModifiedClient {
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
/**
* the main body of the program
* @param argv the hostname
* @throws Exception
*/
public static void main(String argv[]) throws Exception {
/*some strings to be used*/
String command;
String request;
String result;
int flag = 0;
Socket clientSocket = null;
DataOutputStream outToServer = null;
DataInputStream inFromServer = null;
int numOfOutput = 0;
int numOfInput = 0;
/*to establish the connection*/
try {
clientSocket = new Socket(argv[0], 8000);
} catch (IOException ioe) {
System.out.println("can not creat the socket!");
System.exit(1);
}
System.out.println(argv[0] + " is listening to your request:");
/*the input and output stream*/
try {
outToServer =
new DataOutputStream(clientSocket.getOutputStream());
inFromServer =
new DataInputStream(clientSocket.getInputStream());
} catch (Exception ex) {
System.out.println("can not creat stream to server!");
System.exit(1);
}
/*get in the command from console*/
command = stdIn.readLine();
System.out.println("Header:\n");
/*analyse the command*/
try{
if(command.startsWith("GET")) {
request = command + "\r\n" + "\r\n";
numOfOutput = numOfOutput + request.length();
outToServer.write(request.getBytes());//to sent the request to server
result = inFromServer.readLine();//get the response from server
numOfInput = numOfInput + result.length();
try{
do {
System.out.println(result);
result = inFromServer.readLine();
numOfInput = numOfInput + result.length();
} while(result.length() > 0);//to get the header and then display it on the console
} catch(Exception e) {
}
/*transfer the content to a file designated by user*/
System.out.print("\n\n" + "Enter the name of the file to save:");
System.out.flush();
File file = new File(stdIn.readLine());
FileOutputStream outFile = new FileOutputStream(file);
byte[] fileBytes = new byte[1024];
flag = inFromServer.read(fileBytes,0 ,1024);
numOfInput = numOfInput + flag;
outFile.write(fileBytes,0,flag);
while(flag != -1) {
flag = inFromServer.read(fileBytes,0 ,1024);
if(flag == 1024) {
outFile.write(fileBytes,0,1024);
numOfInput = numOfInput + flag;
} else {
try {
outFile.write(fileBytes,0,flag);
} catch (IndexOutOfBoundsException iobe) {
System.out.println(iobe.toString());
}
numOfInput = numOfInput + flag;
}
}
System.out.println("the number of bytes that it sends is " + numOfOutput);
System.out.println("the number of bytes that it receives is " + numOfInput);
outFile.flush();
outFile.close();
}
} catch (Exception exc) {
System.out.println(exc.toString());
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -