java socket传送文件

帮忙写一个传送文件的例子,是由客户端传送给服务端。文件类型不限制。

客户端代码如下:

import java.io.DataOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.net.InetSocketAddress;  
import java.net.Socket;  
  
/** 
 * æ–‡ä»¶å‘送客户端主程序 
 * @author admin_Hzw 
 * 
 */  
public class BxClient {  
      
    /** 
     * ç¨‹åºmain方法 
     * @param args 
     * @throws IOException 
     */  
    public static void main(String[] args) throws IOException {  
        int length = 0;  
        double sumL = 0 ;  
        byte[] sendBytes = null;  
        Socket socket = null;  
        DataOutputStream dos = null;  
        FileInputStream fis = null;  
        boolean bool = false;  
        try {  
            File file = new File("D:/天啊.zip"); //要传输的文件路径  
            long l = file.length();   
            socket = new Socket();    
            socket.connect(new InetSocketAddress("127.0.0.1", 48123));  
            dos = new DataOutputStream(socket.getOutputStream());  
            fis = new FileInputStream(file);        
            sendBytes = new byte[1024];    
            while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {  
                sumL += length;    
                System.out.println("已传输:"+((sumL/l)*100)+"%");  
                dos.write(sendBytes, 0, length);  
                dos.flush();  
            }   
            //虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较  
            if(sumL==l){  
                bool = true;  
            }  
        }catch (Exception e) {  
            System.out.println("客户端文件传输异常");  
            bool = false;  
            e.printStackTrace();    
        } finally{    
            if (dos != null)  
                dos.close();  
            if (fis != null)  
                fis.close();     
            if (socket != null)  
                socket.close();      
        }  
        System.out.println(bool?"成功":"失败");  
    }  
}

服务端代码如下:

import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.net.ServerSocket;  
import java.net.Socket;  
import java.util.Random;  
import com.boxun.util.GetDate;  
  
  
/** 
 * æŽ¥æ”¶æ–‡ä»¶æœåŠ¡ 
 * @author admin_Hzw 
 * 
 */  
public class BxServerSocket {  
      
    /** 
     * å·¥ç¨‹main方法 
     * @param args 
     */  
    public static void main(String[] args) {  
        try {  
            final ServerSocket server = new ServerSocket(48123);  
            Thread th = new Thread(new Runnable() {  
                public void run() {  
                    while (true) {  
                        try {    
                            System.out.println("开始监听...");  
                            /* 
                             * å¦‚果没有访问它会自动等待 
                             */  
                            Socket socket = server.accept();  
                            System.out.println("有链接");  
                            receiveFile(socket);  
                        } catch (Exception e) {  
                            System.out.println("服务器异常");  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            });  
            th.run(); //启动线程运行  
        } catch (Exception e) {  
            e.printStackTrace();  
        }       
    }  
  
    public void run() {  
    }  
  
    /** 
     * æŽ¥æ”¶æ–‡ä»¶æ–¹æ³• 
     * @param socket 
     * @throws IOException 
     */  
    public static void receiveFile(Socket socket) throws IOException {  
        byte[] inputByte = null;  
        int length = 0;  
        DataInputStream dis = null;  
        FileOutputStream fos = null;  
        String filePath = "D:/temp/"+GetDate.getDate()+"SJ"+new Random().nextInt(10000)+".zip";  
        try {  
            try {  
                dis = new DataInputStream(socket.getInputStream());  
                File f = new File("D:/temp");  
                if(!f.exists()){  
                    f.mkdir();    
                }  
                /*   
                 * æ–‡ä»¶å­˜å‚¨ä½ç½®   
                 */  
                fos = new FileOutputStream(new File(filePath));      
                inputByte = new byte[1024];     
                System.out.println("开始接收数据...");    
                while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {  
                    fos.write(inputByte, 0, length);  
                    fos.flush();      
                }  
                System.out.println("完成接收:"+filePath);  
            } finally {  
                if (fos != null)  
                    fos.close();  
                if (dis != null)  
                    dis.close();  
                if (socket != null)  
                    socket.close();   
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-08-16
哈哈,这个我会啊!!!
给你个! 给我分吧!!!
//客户端
package socket;

import java.net.*;
import java.io.*;

/**
* SocketServer从SocketClient接受文件名,将文件发送到SocketServer端保存!
*
*
*/
public class SocketClient {
private static File f = null;
private static FileInputStream fr = null;
private static DataOutputStream dout = null;
private static Socket s = null;

public static void main(String[] args) {
SocketClient sc = new SocketClient();
sc.connectSocketServer(1234);
sc.sendFile("lizhi.txt");
}

/**
* 连接服务器端
*
* @param port
* 要连接的服务器SocketServer端口
*/
public void connectSocketServer(int port) {
try {
s = new Socket(InetAddress.getLocalHost(), port);
} catch (UnknownHostException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}

// 发送文件
public void sendFile(String str) {

byte[] b = new byte[1024];

f = new File(str);
try {
//数据输出流
dout = new DataOutputStream(new BufferedOutputStream(s
.getOutputStream()));

//文件读入流
fr = new FileInputStream(f);
int n = fr.read(b);
while (n != -1) {
//向网络中写入数据
dout.write(b, 0, n);
dout.flush();
//再次读取n字节
n = fr.read(b);
}

//关闭流
fr.close();
dout.close();
} catch (FileNotFoundException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}

}
//服务器端
package socket;

import java.net.*;
import java.io.*;
/**
* Socketserver从客户端读取文件并保存为本地文件!
*
*
*/
public class Socketserver {
private static ServerSocket ss = null;
private static Socket s = null;

private static File f = null;
private static RandomAccessFile fw = null;

public static void main(String[] args) {
Socketserver sk = new Socketserver();
sk.initServer(1234);
sk.getFile();
}
/**
* 初始化服务器端
* @param port
* 服务器端要使用的端口
*/
public void initServer(int port){
try {
ss = new ServerSocket(port);
s = ss.accept();
} catch (IOException e) {

e.printStackTrace();
}
}

// 从SocketClient读取文件
public void getFile() {
byte[] b = new byte[1024];

try {
//定义输入流,s.getInputStream();
InputStream in = s.getInputStream();
DataInputStream din = new DataInputStream(new BufferedInputStream(
in));

//创建要保存的文件
f = new File("copy.txt");
fw = new RandomAccessFile(f, "rw");

int num = din.read(b);
while (num != -1) {
//向文件中写入0~num个字节
fw.write(b, 0, num);
//跳过num个字节再次写入文件
fw.skipBytes(num);
//读取num个字节
num = din.read(b);
}
//关闭输入,输出流
din.close();
fw.close();
} catch (IOException e) {

e.printStackTrace();
}
}

}本回答被提问者采纳