日期:2014-05-20 浏览次数:20838 次
package socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class MyServer {
public static void main(String[] args) throws Exception {
ServerSocket ser=new ServerSocket(10000);
while(true){
Socket s=ser.accept();
System.out.println("服务器连接成功!");
Server st=new Server(s);
st.start();
}
}
}
class Server extends Thread{
private Socket s;
private int i=1;// 文件编号
public Server(Socket s){
this.s=s;
}
public void run(){
while(true){
try{
File file=new File("E:/tomcat/location/webapps/ROOT/test");
ArrayList<String> arr=new ArrayList<String>();
File []files=file.listFiles();
// 向客户端打印文件的列表 , 并把文件的名字存放到数组集合中
PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
for (File f : files) {
if(f.isFile()){
String name=f.getName();
arr.add(name);
pw.println(""+(i++)+" "+name);
pw.flush();
}
}
pw.close();
// 读取从Client输的数字
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true){
String number=br.readLine();
System.out.println(number);
if(number==null){
System.out.println(number);
break;
}
}
br.close();
}catch(Exception e){
}
}
}
}