📄 modifiedclient.txt
字号:
www.pudn.com > Exercise2.rar > ModifiedClient.java
//200532580182 pengxu
import java.io.*;
import java.net.*;
public class ModifiedClient {
//the client socket used to connect to server
private Socket clientSocket;
//read the user input from keyboard
BufferedReader inFromKeyBoard;
//get the information response by the server
BufferedReader inFromServer;
//send the user input to the sever
DataOutputStream outToServer;
public ModifiedClient(){
this.clientSocket=null;
}
//connect to the server
public void connect(String host,int port){
try{
this.clientSocket=new Socket(host,port);
//read from keyboard
this.inFromKeyBoard=new BufferedReader
(new InputStreamReader(System.in));
//read from the client socket
this.inFromServer=new BufferedReader
(new InputStreamReader(clientSocket.getInputStream()));
//output to server socket
this.outToServer=new DataOutputStream
(clientSocket.getOutputStream() );
}catch(Exception e){
e.printStackTrace();
}
}
public void close(){
try{
//close the socket
this.clientSocket.close();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String [] args) throws Exception{
if(args.length!=1){
System.out.println("Usage: Client <server>");
System.exit(0);
}
else{
try{
double sendBytes;
double recieveBytes;
final int port=80;
ModifiedClient client=new ModifiedClient();
//connnect to the user defined host(argv[0]) use port 80
client.connect(args[0], port);
System.out.println(args[0] + " is listening to you request:");
//read the user input from keyboard assign to s
String s=client.inFromKeyBoard.readLine();
s+="\r\n" + "\r\n";
//send s to server
client.outToServer.writeBytes(s);
//get the sendBytes
sendBytes=s.length();
//get the response header and show to the user
String file="";
String temp=file;
int i=0;
boolean flag=true;
for(int j=0; flag&amt;&amt;((j=client.inFromServer.read())!=-1);){
switch(j)
{
case 13: // '\r'
break;
case 10: // '\n'
if(j == i)
{
flag = false;
} else
{
i = j;
file+="\r\n";
}
break;
default:
i = j;
file+=(char)j;
break;
}
}
System.out.println("Header:");
System.out.println("");
System.out.println(file);
//get the recieveBytes
recieveBytes=file.length();
file="";
temp=client.inFromServer.readLine();
//get the response context
while(temp!=null){
file=file + "\r\n"+temp;
temp=client.inFromServer.readLine();
}
// save the response text to a file
System.out.println("Enter the name of the file to save: ");
String name=client.inFromKeyBoard.readLine();
FileOutputStream filename=new FileOutputStream(name);
filename.write(file.getBytes());
recieveBytes+=file.length();
System.out.println("Send bytes: "+sendBytes);
System.out.println("recieve bytes: "+recieveBytes);
filename.flush();
filename.close();
client.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -