?? client.java~
字號:
/**
* @(#)Server.java
*
* @author Xia Chang'an
* @version 1.0
*/
import java.io.*;
import java.net.*;
public class Client
{
/**
* The port of the socket
*/
private static int port = 80;
private static String CRLF = "\r\n";
public static void main(String argv[]) throws UnknownHostException, IOException
{
/**
* The request command.
*/
String command = "";
/**
* The header line.
*/
String header = "";
Socket clientSocket;
byte [] bytes;
/**
* ensure the argument value
*/
if(argv.length != 1)
{
System.err.println("Usage: Client <server>");
System.exit(0);
}
/**
* construct a socket banding to the port.
*/
clientSocket = new Socket(argv[0], port);
/**
* read from the user input.
*/
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
/**
* read from the server.
*/
DataInputStream inFromServer =
new DataInputStream(clientSocket.getInputStream());
/**
* output to the server.
*/
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
/**
* print the promot information.
*/
System.out.println(argv[0] + " is listening to your request:");
/**
* read a line from the user input.
*/
command = inFromUser.readLine();
bytes = (command + CRLF + CRLF).getBytes();
/**
* write the bytes to the server.
*/
outToServer.write(bytes, 0, bytes.length);
/**
* flush the stream
*/
outToServer.flush();
/**
* Get from the respond header from the server.
*/
String line;
while((line = inFromServer.readLine()).length() != 0)
{
header += line;
header += '\n';
}
/**
* Print the header to the terminal.
*/
System.out.println("Header: \n");
System.out.print(header + "\n");
System.out.flush();
System.out.print("Enter the name of the file to save: ");
System.out.flush();
String filename = inFromUser.readLine();
FileOutputStream fileOut = null;
/**
* creat a new file.
*/
if(!filename.isEmpty())
{
fileOut = new FileOutputStream(filename);
}
else
{
System.err.println("File name empty! Exit.");
System.exit(0);
}
try
{
/**
* print the respond content to the file.
*/
byte[] buffer = new byte[1];
while(inFromServer.read(buffer, 0, buffer.length) != -1)
{
fileOut.write(buffer);
}
} catch(NullPointerException e) {
e.printStackTrace();
}
System.out.println("The content has been saved in the file '" + filename + "'.");
/**
* Close the stream and the socket.
*/
fileOut.close();
clientSocket.close();
inFromServer.close();
outToServer.close();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -