android与socket通讯(三)

来源:互联网 发布:知之深爱读书笔记 编辑:程序博客网 时间:2024/05/29 02:30
public class Test {/** * @param args * @throws FileNotFoundException  */public static void main(String[] args) throws Exception {FileInputStream fs = new FileInputStream(new File("D:\\test.dat"));{//一般是不用这种方法。返回的是下一个数据字节的大小0表示有空格,可以以此为依据划分帧int i=fs.read();while((i=fs.read())!=-1){System.out.println(i);   }}}}

使用socket作为服务器。

我们现在使用socket来模拟服务器向客户端发送二进制文件。还没有一种直接的方法可以直接将二进制文件发送到客户端。这是因为服务器要发送文件,就必须要一个File对象。此外在输出流上面又必须使用socket的输出流。要同时满足这两个条件,仅仅使用一个类来完成是不行的。PrintWrite方法只能被用于字符串流。

所以,先要将文件读入一个缓存中,输出流再从缓存中读数据在发送出去。

public class Server {public static void main(String[] args) throws IOException {ServerSocket clientServer=new ServerSocket(6666);Socket  socket=clientServer.accept();FileInputStream fileInputStream=new FileInputStream(new File("D:\test.dat"));OutputStream outputStream=socket.getOutputStream();  byte[] buffer=new byte[1024];//read与wirte方法是可以阻塞的方法,即可以自动循环的方法。 int  flag=fileInputStream.read(buffer); while((flag=fileInputStream.read(buffer))!=-1){ outputStream.write(buffer);  }}}public class ClientSocket{   public static void main(String[] args)throws Exception{   Socket  serverSocket=new Socket(InetAddress.getByName("localhost"), 6666);InputStream inputStream=serverSocket.getInputStream();File file=new File("E:\\copy.apk");FileOutputStream fileOutputStream=new FileOutputStream(file);byte[] buffer=new byte[1024];int flag=0;while((flag=inputStream.read(buffer))!=-1){fileOutputStream.write(buffer);}}   }

这样,我们就能传输二进制文件了。



原创粉丝点击