package j2se.core.net.tcp.command;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8888);
while (true) {
Socket socket = null;
socket = server.accept();
Thread t = new Thread(new ServerRunner(socket));
t.start();
}
}
}
class ServerRunner implements Runnable {
private Socket socket;
public ServerRunner(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
DataInputStream input = new DataInputStream(socket.getInputStream());
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream()));
while (true) {
// 接收客户机传递过来的指令
String command = input.readUTF();
// 处理指令
String[] array = command.split(":");
StringBuilder builder = new StringBuilder();
if ("GET".equals(array[0])) {
// 加载文件的处理
File file = new File(array[1]);
BufferedReader reader = new BufferedReader(new FileReader(file));
String fileContent = null;
while ( (fileContent = reader.readLine()) != null ) {
builder.append(fileContent);
builder.append("
");
}
} else if ("TIME".equals(array[0])) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.append(df.format(new Date()));
builder.append("
");
} else {
builder.append("未知指令");
builder.append("
");
}
builder.append("EOF
");
// 回应客户处理结果
output.write(builder.toString());
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package j2se.core.net.tcp.command;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("127.0.0.1", 8888);
Thread t = new Thread(new ClientRunner(socket));
t.start();
}
}
class ClientRunner implements Runnable {
private Socket socket;
public ClientRunner(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DataOutputStream output = new DataOutputStream(socket
.getOutputStream());
while (true) {
// GET:src/Demo.java
// 接收键盘输入的指令
String command = scanner.nextLine();
// 发送指令
output.writeUTF(command);
// 处理回应
while (true) {
String response = input.readLine();
if ("EOF".equals(response))
break;
System.out.println(response);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}