团队博客16
今天实现了在同一WiFi网络下通过IP地址对图片的传输,但是只能传输小于1M的图片,对于超过1M的图片会因为连接时间过长而超时,不能传送成功。如果解决了大图片的传输问题,那么视频和音频是不是也就能很好的进行传输了呢?
下面是传输小图片的代码(简单易懂,效率不太好):
代码引用于:http://blog.csdn.net/yuankundong/article/details/51489823;
接收端:
public void ReceiveFile(){ try{ Socket name = server.accept(); InputStream nameStream = name.getInputStream(); InputStreamReader streamReader = new InputStreamReader(nameStream); BufferedReader br = new BufferedReader(streamReader); String fileName = br.readLine(); br.close(); streamReader.close(); nameStream.close(); name.close(); SendMessage(0, "正在接收:" + fileName); Socket data = server.accept(); InputStream dataStream = data.getInputStream(); String savePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName; File f=new File(savePath); int i=0; while(f.exists()) {//如果上传的文件发生重名,进行改名 i++; fileName = fileName.substring(0, fileName.indexOf(".")-1)+""+i+""+ fileName.substring(fileName.indexOf(".")); savePath = Environment.getExternalStorageDirectory().getPath() + "/" + fileName; f=new File(savePath); } FileOutputStream file = new FileOutputStream(savePath, false); byte[] buffer = new byte[1024]; int size = -1; while ((size = dataStream.read(buffer)) != -1){ file.write(buffer, 0 ,size); } file.close(); dataStream.close(); data.close(); SendMessage(0, fileName + "接收完成"); }
发送端:
public void SendFile(ArrayList<String> fileName,ArrayList<String> path, String ipAddress, int port){ try { for (int i = 0; i < fileName.size(); i++){ Socket name = new Socket(ipAddress, port); OutputStream outputName = name.getOutputStream(); OutputStreamWriter outputWriter = new OutputStreamWriter(outputName); BufferedWriter bwName = new BufferedWriter(outputWriter); bwName.write(fileName.get(i)); bwName.close(); outputWriter.close(); outputName.close(); name.close(); SendMessage(0, "正在发送" + fileName.get(i)); Socket data = new Socket(ipAddress, port); OutputStream outputData = data.getOutputStream(); FileInputStream fileInput = new FileInputStream(path.get(i)); int size = -1; byte[] buffer = new byte[1024]; while((size = fileInput.read(buffer, 0, 1024)) != -1){ outputData.write(buffer, 0, size); } outputData.close(); fileInput.close(); data.close(); SendMessage(0, fileName.get(i) + " 发送完成"); }