android与socket通讯(三)

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);
}

}   
}

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值