socket多客户端上传文件--代码

public class FileServer {
public static void main(String[] args) throws Exception {
ServerSocket ss=new ServerSocket(10007);
while(true){
Socket s=ss.accept();
new Thread(new FileThread( s)).start();
}
}
}
class FileThread implements  Runnable {
private Socket s;
FileThread(Socket s){
this.s=s;
}
@Override
public void run() {
String ip=s.getInetAddress().getHostAddress();
try {
int count=1;
System.out.println(ip+"....连接进了");
InputStream in=s.getInputStream();
File f=new File(ip+"("+count+")"+".txt");
while(f.exists())
f=new File(ip+"("+count+++")"+".txt");
FileOutputStream fos=new FileOutputStream(f);
byte[] buf=new byte[1024];
int len=0;
while((len=in.read(buf))!=-1){
fos.write(buf, 0, len);
}
OutputStream out=s.getOutputStream();
out.write("上传成功".getBytes());
fos.close();
s.close();
} catch (Exception e) {
System.out.println(ip+"出错了");
}
}
}
class FileClient{
public static void main(String[] args) throws Exception {
if(args.length!=1){
System.out.println("输入正确文件路径");
return ;
}
File file=new File(args[0]);
if(!file.exists()||!file.isFile()){
System.out.println("输入正确文件路径");
return ;
}
Socket s=new Socket("127.0.0.1",10007);
FileInputStream fis=new FileInputStream(file);
OutputStream out=s.getOutputStream();
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1){
out.write(buf, 0, len);
}
s.shutdownOutput();
InputStream in=s.getInputStream();
byte[] bufIn=new byte[1024];
int num=in.read(bufIn);
System.out.println(new String(bufIn,0,num));
fis.close();
}
}

你可能感兴趣的:(socket)