1 Buổi 2 - Bài 3 Mon Mar 11, 2013 11:13 pm
Admin
Admin
Phần Server:
Phần Client:
- Code:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server2_3 {
public static void main(String[] args) throws IOException {
int PORT=2000;
ServerSocket ss = new ServerSocket(PORT);
System.out.println("SERVER is Started in PORT "+PORT+".");
while (true){
Socket s = ss.accept();
System.out.println("Client "+s.getInetAddress().toString() +" in port "+s.getLocalPort()+" has been connected!");
Client c = new Client(s);
c.start();
}
}
}
class Client extends Thread{
Socket s;
Client(Socket s){
this.s = s;
}
public void run(){
try{
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream());
while (true){
//Read a String
String command = in.nextLine();
//Cancel Thread if revice "exit"
if (command.toUpperCase().equals("EXIT")){
System.out.println("Client "+s.getInetAddress().toString() +" in port "+s.getLocalPort()+" has been disconnected!");
break;
}
//Process
String[] recive = command.split(" ");
if (recive[0].toUpperCase().equals("LIST")){
File file = new File(recive[1]);
if (file.exists()){
File[] listFile = file.listFiles();
String ans="OK,";
if (listFile!=null){
for (File f : listFile){
if (f.isDirectory())
ans+="+"+f.getName()+",";
else
ans+="-"+f.getName()+",";
}
}
else{
ans+="EMPTY";
}
out.println(ans);
out.flush();
}
else{
out.println("FAILE,NOT_FOUND");
out.flush();
}
}else{
out.println("FAILE,ERROR_COMMAND");
out.flush();
}
String ans="";
}
s.close();
}catch(IOException e){
System.out.println("Client is disconnect!");
}
}
}
Phần Client:
- Code:
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client2_3 {
public static void main(String[] args) throws UnknownHostException {
int PORT=2000;
System.out.println("Client started in PORT "+PORT+".");
try{
Socket s = new Socket("127.0.0.1", PORT);
Scanner in = new Scanner(s.getInputStream());
PrintWriter out = new PrintWriter(s.getOutputStream());
Scanner keyboard = new Scanner(System.in);
System.out.println("EXIT to Stop Application");
while (true){
System.out.print("Enter command:");
String command = keyboard.nextLine();
if (command.toUpperCase().equals("EXIT")){
out.println("EXIT");
out.flush();
break;
}
out.println(command);
out.flush();
String[] ans = in.nextLine().split(",");
if (ans[0].equals("OK")){
if (ans[1].equals("EMPTY")){
System.out.println("Folder is Empty");
}
else{
System.out.println(command.split(" ")[1]+": ");
for (int i=1;i<ans.length;i++)
System.out.println(" "+ans[i]);
}
}else{
if (ans[1].equals("ERROR_COMMAND"))
System.out.println("Error command!!!");
else if (ans[1].equals("NOT_FOUND"))
System.out.println("Directory is not found!");
}
}
s.close();
}
catch(IOException e){
}
}
}