通过Socket实现文件传输(Java)

这个简单的例子将演示应用Java实现客户端与服务器端传输文件的方法。

服务器端源代码:

01. import java.net.*;
02. import java.io.*;
03.   
04. public class FileServer {
05.   public static void main (String [] args ) throws IOException {
06.     // create socket
07.     ServerSocket servsock = new ServerSocket(13267);
08.     while (true) {
09.       System.out.println("Waiting...");
10.   
11.       Socket sock = servsock.accept();
12.       System.out.println("Accepted connection : " + sock);
13.   
14.       // sendfile
15.       File myFile = new File ("source.pdf");
16.       byte [] mybytearray  = new byte [(int)myFile.length()];
17.       FileInputStream fis = new FileInputStream(myFile);
18.       BufferedInputStream bis = new BufferedInputStream(fis);
19.       bis.read(mybytearray,0,mybytearray.length);
20.       OutputStream os = sock.getOutputStream();
21.       System.out.println("Sending...");
22.       os.write(mybytearray,0,mybytearray.length);
23.       os.flush();
24.       sock.close();
25.       }
26.     }
27. }

客户端源代码:

01. import java.net.*;
02. import java.io.*;
03.   
04. public class FileClient{
05.   public static void main (String [] args ) throws IOException {
06.     int filesize=6022386; // filesize temporary hardcoded
07.   
08.     long start = System.currentTimeMillis();
09.     int bytesRead;
10.     int current = 0;
11.     // localhost for testing
12.     Socket sock = new Socket("127.0.0.1",13267);
13.     System.out.println("Connecting...");
14.   
15.     // receive file
16.     byte [] mybytearray  = new byte [filesize];
17.     InputStream is = sock.getInputStream();
18.     FileOutputStream fos = new FileOutputStream("source-copy.pdf");
19.     BufferedOutputStream bos = new BufferedOutputStream(fos);
20.     bytesRead = is.read(mybytearray,0,mybytearray.length);
21.     current = bytesRead;
22.   
23.     // thanks to A. Cádiz for the bug fix
24.     do {
25.        bytesRead =
26.           is.read(mybytearray, current, (mybytearray.length-current));
27.        if(bytesRead >= 0) current += bytesRead;
28.     } while(bytesRead > -1);
29.   
30.     bos.write(mybytearray, 0 , current);
31.     bos.flush();
32.     long end = System.currentTimeMillis();
33.     System.out.println(end-start);
34.     bos.close();
35.     sock.close();
36.   }
37. }

查看原文 Real’s Java How To

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值