博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java sending and receiving file (byte[]) over sockets
阅读量:4939 次
发布时间:2019-06-11

本文共 2120 字,大约阅读时间需要 7 分钟。

 

Server

publicclassServer{
/** * @param args the command line arguments */ public static void main(String[] args)throwsIOException{
ServerSocket serverSocket =null;try{
serverSocket =newServerSocket(4444); }catch(IOException ex){
System.out.println("Can't setup server on this port number. "); } Socket socket =null; InputStream is =null; FileOutputStream fos =null; BufferedOutputStream bos =null; int bufferSize =0;try{
socket = serverSocket.accept();} catch(IOException ex){
System.out.println("Can't accept client connection. "); }try{
is = socket.getInputStream(); bufferSize = socket.getReceiveBufferSize();     System.out.println("Buffer size: "+ bufferSize); }catch(IOException ex){
System.out.println("Can't get socket input stream. "); }try{
fos =newFileOutputStream("M:\\test2.xml"); bos =newBufferedOutputStream(fos);   }catch(FileNotFoundException ex){
    System.out.println("File not found. ");   }   byte[] bytes =newbyte[bufferSize];   int count;   while((count = is.read(bytes))>0){
bos.write(bytes,0, count); } bos.flush(); bos.close(); is.close(); socket.close(); serverSocket.close();}

}

and the Client

publicclassClient{
/** * @param args the command line arguments */ public static void main(String[] args)throwsIOException{
  Socket socket =null;   String host ="127.0.0.1"; socket =newSocket(host,4444);   File file =newFile("M:\\test.xml");// Get the size of the file   long length = file.length();   if(length >Integer.MAX_VALUE){
    System.out.println("File is too large.");   }   byte[] bytes =newbyte[(int) length];   FileInputStream fis =newFileInputStream(file);   BufferedInputStream bis =newBufferedInputStream(fis);   BufferedOutputStream out =newBufferedOutputStream(socket.getOutputStream());   int count;   while((count = bis.read(bytes))>0){
out.write(bytes,0, count);   } out.flush(); out.close(); fis.close(); bis.close(); socket.close();}

}

转载于:https://www.cnblogs.com/songtzu/archive/2013/02/25/2932216.html

你可能感兴趣的文章
实验十 指针2
查看>>
常见HTTP状态码
查看>>
vim 空格和换行的删除和替换
查看>>
ionic 入门学习
查看>>
[python]pickle和cPickle
查看>>
末日了,天是灰色的。
查看>>
Vuejs vm对象详解
查看>>
自定义RatingBar的一个问题(只显示显示一个星星)
查看>>
剑指Offer--二叉树的镜像
查看>>
PAT-BASIC-1031-查验身份证
查看>>
Python笔记5----集合set
查看>>
连连看小游戏
查看>>
js二级联动
查看>>
谜题32:循环者的诅咒
查看>>
RMI
查看>>
动态切换多数据源的配置
查看>>
win7电脑调整分区后分区不见的文件寻回法子
查看>>
《第一行代码》学习笔记2-Android开发特色
查看>>
bzoj3396 [Usaco2009 Jan]Total flow 水流
查看>>
20165231 2017-2018-2 《Java程序设计》第3周学习总结
查看>>