Sending Image Through Socket with Java
SERVER
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.*; public class imageServer { public static void main(String[] args) throws IOException { File testF = new File("/home/ipopp/Public/smalltest/tes.jpg"); ServerSocket server = new ServerSocket(9090); try { System.out.println("reading file"); Socket socket = server.accept(); FileInputStream file = new FileInputStream(testF); BufferedInputStream ins = new BufferedInputStream(file); BufferedOutputStream outs = new BufferedOutputStream(socket.getOutputStream()); byte[] buffer = new byte[4096]; long bytesRead; while( (bytesRead = ins.read(buffer)) != -1) { outs.write(buffer,0, (int) bytesRead); } outs.flush(); outs.close(); ins.close(); } catch (FileNotFoundException e) { } } }
CLIENT
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.InputStreamReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.*; /** * * @author ipopp */ public class imageClient { public static void main(String[] args) throws IOException { File result = new File("/home/ipopp/Public/smalltest/result/result.jpg"); Socket socket = new Socket("127.0.0.1",9090); FileOutputStream fos = new FileOutputStream(result); BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(fos); int bytesRead =0; byte[] buffer = new byte[4092]; int off = 0; int length; while ( (bytesRead = bis.read(buffer)) != -1) { int read; bos.write(buffer,0,bytesRead); } fos.close(); bis.close(); }
Komentar
Posting Komentar