【JAVA】Socket文件上传遇到的问题!~

同事做的socket通信上传文件有问题。让我改。发现每次得到文件名称。但是流已经写入了。文件名是第一次上传的文件名字。网上看了下就这样写的。也不知道原因,这里把错误代码贴下。大家帮我看下什么原因。。。新代码是网上找到的创建了个线程就好了。

服务器端:

错误代码:

package com.zssoft.mis.struts2.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
	private ServerSocket server = null;
	Socket socket = null;
	
	public void getData(String savePath,int port) {
		int progress = 0;
        
		try {
			// 建立socket监听。
			server = new ServerSocket(port);
			
		while ( (socket = server.accept()) != null) {
			// 建立socket输入流  
			DataInputStream inputStream = new DataInputStream(new BufferedInputStream(socket  
                    .getInputStream()));  
            // 缓冲区大小  
            int bufferSize = 8192;  
            // 缓冲区  
            byte[] buf = new byte[bufferSize];  
            int passedlen = 0;  
            long len = 0;  
            // 获取文件名称
            if( !savePath.contains("."))
            savePath += inputStream.readUTF();  
            DataOutputStream fileOut = new DataOutputStream(  
                    new BufferedOutputStream(new BufferedOutputStream(  
                            new FileOutputStream(savePath))));  
            // 获取文件长度  
            len = inputStream.readLong();  
  
            System.out.println("文件的长度为:" + len + "  KB");  
            System.out.println("开始接收文件!");  
  
            // 获取文件,下边是进度条。
            System.out.print("#>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#");
            System.out.println(">>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#>>>>>>>>>#");  
            while (true) {  
                int read = 0;  
                if (inputStream != null) {  
                    read = inputStream.read(buf);  
                }  
                passedlen += read;
                if (read == -1) {  
                    break;  
                }

                if((int)(passedlen * 100.0 / len)-progress > 0){
                	        progress = (int)(passedlen * 100.0 / len);
//                	        System.out.println("文件接收了" + progress + "%"); 
                	        System.out.print(">");
                			}

                fileOut.write(buf, 0, read);  
            } 
            System.out.println();
            System.out.println("接收完成,文件存为: " + savePath);  
            fileOut.close();  
        	} 
		}catch (Exception e){
			System.err.println("File Server Excetption: " + e);
			e.printStackTrace();
		}		
	}
	
	public static void main(String[] args) {
    	//函数运行之前要指定待传送文件地址。
    	/*if(args.length != 2){
    		System.err.println("Usage: FileServer <save path> <port>");
    		System.exit(-1);
    	}*/
    	new FileServer().getData("F:\\", 9600); 
      //  new FileServer().getData(args[0], Integer.parseInt(args[1])); 
	}

}

正确代码:


package com.zssoft.mis.struts2.util;

import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {
	protected int listenPort = 9600;

	public static void main(String[] args) {
		FileServer server = new FileServer();
		server.acceptConnections();
	}

	/**
	 * 建立链接
	 * 
	 */
	public void acceptConnections() {
		try {
			ServerSocket server = new ServerSocket(listenPort);
			Socket socket = null;
			while (true) {
				socket = server.accept();
				// handleConnection(socket);
				new ServerThread(socket).start();
			}
		} catch (Exception e) {
			System.out.println("Unable to bind to port " + listenPort);
		}

	}
}

package com.zssoft.mis.struts2.util;

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

public class ServerThread extends Thread {
	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}

	public void run() {

		try {

			DataInputStream inputStream = null;
			try {
				inputStream = new DataInputStream(new BufferedInputStream(
						socket.getInputStream()));
			} catch (Exception e) {
				System.out.print("接收消息缓存错误\n");
				return;
			}
			try {
				// 本地保存路径,文件名会自动从服务器端继承而来最好是web工程里的一个路径。
				String savePath = "F:\\";
				int bufferSize = 8192;
				byte[] buf = new byte[bufferSize];
				long len = 0;
				savePath += inputStream.readUTF();
				DataOutputStream fileOut = new DataOutputStream(
						new BufferedOutputStream(new BufferedOutputStream(
								new FileOutputStream(savePath))));
				len = inputStream.readLong();
				System.out.println("文件的长度为:" + len + "\n");
				System.out.println("开始接收文件!" + "\n");
				while (true) {
					int read = 0;
					if (inputStream != null) {
						read = inputStream.read(buf);
					}
					if (read == -1) {
						break;
					}
					// System.out.println(buf.toString());
					fileOut.write(buf, 0, read);
				}
				System.out.println("接收完成,文件存为" + savePath + "\n");
				fileOut.flush();
				fileOut.close();
				inputStream.close();
			} catch (Exception e) {
				System.out.println("接收消息错误" + "\n");
				return;
			}
		} catch (Exception e) {
			System.out.println("Error handling a client: " + e);
		}

	}

}

客户端代码:


package com.zssoft.mis.struts2.util;

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

public class FileClient {
	public void sendData(String filepath, String IP, int port) {
		int progress = 0;
        // socket输出流  
        DataOutputStream os = null;  
        // 文件输入流  
        DataInputStream is = null;  
        // 建立socket连接  
        Socket socket = null;  
        try {  
            // 选择进行传输的文件  
            File file = new File(filepath);  
  
            // 建立socket连接
            socket = new Socket(IP, port);
  
            os = new DataOutputStream(socket.getOutputStream());  
  
            // 将文件名及长度传给服务器端。
            os.writeUTF(file.getName());  
            os.flush();  
            os.writeLong((long) file.length());  
            os.flush();  
  
            is = new DataInputStream(new BufferedInputStream(  
                    new FileInputStream(filepath)));  
            // 缓冲区大小  
            int bufferSize = 8192;  
            // 缓冲区  
            byte[] buf = new byte[bufferSize]; 
            
            // 传输文件  
            while (true) {  
                int read = 0;  
                if (is != null) {  
                    read = is.read(buf);  
                }  
                progress += Math.abs(read);
                if (read == -1) {  
                    break;  
                }  
                os.write(buf, 0, read); 
                //发送进度。
                System.out.println("文件已发送:" + (int)(100.0*progress/file.length()) + "%");
            }          
            os.flush(); 
            System.out.println("\n文件已上传完毕!");
	}catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        // 关闭所有连接  
        try {  
            if (os != null)  
                os.close();  
        } catch (IOException e) {  
        	}  
        try {  
            if (is != null)  
                is.close();  
        } catch (IOException e) {  
        	}  
        try {  
            if (socket != null)  
                socket.close();  
        } catch (IOException e) {  
        	}  
        } 
    }  
	
	public static void main(String[] args) {
		new FileClient().sendData("D:\\aa.swf", "10.78.151.188", 9600);
	}

}
源代码下载: http://download.csdn.net/detail/hateson/6198049


转帖请注明原帖地址:http://blog.csdn.net/hateson/article/details/10927871



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值