Java Socket客户端服务器之间的文件传输

2 篇文章 0 订阅

主体参考了http://www.blogjava.net/sterning/archive/2007/10/13/152508.htmlhttp://blog.csdn.net/defonds/article/details/7971259

while循环的部分参考的是http://blog.csdn.net/YidingHe/article/details/3955055

主要写从客户端上传到服务器的过程,下载是一样的。删除了多余的代码后没有测试,如有bug请查参考文献。

客户端类:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {
	public static final String IP_ADDR = "localhost";//Server address
	public static final int PORT = 12345;//Server end port number
	
    public static void main(String[] args) {  
    	uploadFile(<filepath>, <filename>);
    }  
    
    private static boolean uploadFile(String path, String filename){
    	boolean tag = true;
    	System.out.println("Starting Client...");  
        System.out.println("When receiving \"upload successful\" from server, client will be terminated\n"); 
        while (true) {  
        	Socket socket = null;
        	try {
        		//Create a socket and connect to the specific port number in the address
	        	socket = new Socket(IP_ADDR, PORT);  
	              
	            //Read data from the server
	            DataInputStream input = new DataInputStream(socket.getInputStream());  
	            //Send data to server
	            DataOutputStream out = new DataOutputStream(socket.getOutputStream());  
	            System.out.println("Uploading file... \t");  
	            
	            DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)));
	            File file = new File(path);
	            long length = file.length();
	            out.writeUTF(filename);
	            out.flush();
				out.writeLong((long)file.length());
				out.flush();
				int bufferSize = 8192;
				byte[] buf = new byte[bufferSize];
				long count = 0;
				while(count < length){
					int read = 0;
					if(fis != null){
						read = fis.read(buf);
					}
					if(read == -1){
						break;
					}
					out.write(buf, 0 , read);
					count += (long)read;
				}
				System.out.println("Send file length: " + count);
				String ret = input.readUTF();

				fis.close();
				// If receive "upload successful" from server, disconnect
				if ("upload successful".equals(ret)) {  
					tag = true;
					System.out.println("upload successful");
					System.out.println("Client will be closed");  
					Thread.sleep(500);  
					out.close();
					input.close();
					break;  
				}
				else{
					tag = false;
					System.out.println("upload failed");
					System.out.println("Client will be closed");  
					Thread.sleep(500);  
					out.close();
					input.close();
					break;  
        		}
        	} 
        	catch (Exception e) {
        		System.out.println("Client exception: " + e.getMessage()); 
        	} 
        	finally {
        		if (socket != null) {
        			try {
						socket.close();
						return tag;
					} 
        			catch (IOException e) {
						socket = null; 
						System.out.println("Client finally exception: " + e.getMessage()); 
						return false;
					}
        		}
        	}
        }
		return false;  
    }
}
    

服务器类:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Date;


public class Server {
	public static final int PORT = 12345;//Listening port number   
	
    public static void main(String[] args) {  
        System.out.println("Starting server...\n");  
        Server server = new Server();  
        server.init();  
    }  
  
    public void init() {  
        try {  
            ServerSocket serverSocket = new ServerSocket(PORT);  
            while (true) {  
                //Client and server are connected.
                Socket client = serverSocket.accept();  
                // Process this connection
                new HandlerThread(client);  
            }  
        } catch (Exception e) {  
            System.out.println("Server exception: " + e.getMessage());  
        }  
    }  
  
    private class HandlerThread implements Runnable {  
        private Socket socket;  
        public HandlerThread(Socket client) {  
            socket = client;  
            new Thread(this).start();  
        }  
  
        public void run() {  
            try {     
                // Read data from client
            	DataInputStream input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            	DataOutputStream out = new DataOutputStream(socket.getOutputStream());  
            	String clientInputStr = input.readUTF();//Corresponds to the write method in client side, otherwise it will EOFException
                // Process data from client  
                System.out.println("Content sent by client:" + clientInputStr);  
                String s=null;
               
				String fileName = input.readUTF();                	
				
				int bufferSize = 8192;
				byte[] buf = new byte[bufferSize];
				int passedlen = 0;
				long len = 0;
				len = input.readLong();
				String savePath = <targetPath> + fileName;
				DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)));
				System.out.println("Receive file length " + len);
				System.out.println("Start to receive file!" + "\n");
				long count = 0;
				while(count < len){
					int read = 0;
					if(input != null){
						read = input.read(buf);
					}
					passedlen += read;
					if(read == -1){
						break;
					}
					if(passedlen * 100 / len > ((passedlen - read) * 100 / len))
						System.out.println("File received " +  (passedlen * 100/ len) + "%");
					fileOut.write(buf, 0, read);
					count += (long)read;
				}
				fileOut.flush();
				System.out.println("Uploading completed!");
				fileOut.close();
				
				s = "upload successful";				
                
                // Respond to client
                System.out.println("Server: " + s);
                out.writeUTF(s);  
                out.close();  
                input.close();  
            } catch (Exception e) {  
                System.out.println("Server run exception: " + e.getMessage());  
            } finally {  
                if (socket != null) {  
                    try { 

                    } 
                    catch (Exception e) {  
                        socket = null;  
                        System.out.println("Server finally exception: " + e.getMessage());  
                    }  
                }  
            } 
        } 
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值