android与socket通讯(三)
16lz
2021-01-23
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);}} }
这样,我们就能传输二进制文件了。
更多相关文章
- Android Studio 3.0找不到Android Device Monitor的解决方法
- android 5.1 usb调试默认关闭设置方法
- Android--ListView滑动时出现黑屏解决方法(整合)
- Android不错的图片压缩方法
- Android延时任务方法
- Android listview中使用button解决方法
- android 判断横竖屏的方法
- Android 以流的方式读取服务器图片文件