//服务器端可以支持多个客户端同时上传,用到了多线程
/**
* 文件传输,客户端
* @aurth anyx
*/
//package per.anyx.ftp
import java.net.*
import java.io.*
public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file")
System.exit(0)
}
File file = new File(args[2])
if(!file.exists() || !file.isFile()){
System.out.println("File \"" + args[2] + "\" does not exist or is not a normal file.")
System.exit(0)
}
Socket s = null
FileInputStream in = null
OutputStream out = null
try{
s = new Socket(args[0], Integer.parseInt(args[1]))
in = new FileInputStream(file)
out = s.getOutputStream()
byte[] buffer = new byte[1024*8]
int len = -1
System.out.println("File tansfer statr...")
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len)
}
System.out.println("File tansfer complete...")
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
System.exit(1)
}finally{
try{
if(in != null) in.close()
if(out != null) out.close()
if(s != null) s.close()
}catch(Exception e){}
}
}
}
/**
* 文件传输,服务器端
* @aurth anyx
*/
//package per.anyx.ftp
import java.net.*
import java.io.*
public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port")
System.exit(0)
}
ServerSocket ss = null
try{
ss = new ServerSocket(Integer.parseInt(args[0]))
System.out.println("FtpServer start on port ..." + args[0])
while(true){
Socket s = ss.accept()
new FtpThread(s).start()
System.out.println(s.getInetAddress().getHostAddress() + " connected.")
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
}finally{
try{
if(ss != null) ss.close()
}catch(Exception e){}
}
}
}
class FtpThread extends Thread{
Socket s
long fileName = 0
public FtpThread(Socket s){
this.s = s
}
public void run(){
FileOutputStream out = null
InputStream in = null
File file = null
do{
file = new File("" + (fileName++))
}while(file.exists())
try{
out = new FileOutputStream(file)
in = s.getInputStream()
byte[] buffer = new byte[1024*8]
int len = -1
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len)
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage())
}finally{
try{
if(in != null) in.close()
if(out != null) out.close()
if(s != null) s.close()
System.out.println(s.getInetAddress().getHostAddress() + " connect closed..")
}catch(Exception e){}
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)