Android-Based on Socket and uploading images to the client,
In the recent project, when the client and Socket need to transmit data to each other, they need to transmit images to each other. So let's make a summary so that we can not forget it, but also hope to help you.
First run the client code:
Upload a single photo in the camera based on the image name (this method is encapsulated by yourself)
The parameter represents the photo path.
private void upload(String path) { int length = 0; byte[] sendBytes = null; Socket socket = null; DataOutputStream dos = null; FileInputStream fis = null; try { try { socket = new Socket(ip,duankou); dos = new DataOutputStream(socket.getOutputStream()); File file = new File(filename); fis = new FileInputStream(file); sendBytes = new byte[1024]; while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) { dos.write(sendBytes, 0, length); dos.flush(); } } finally { if (dos != null) dos.close(); if (fis != null) fis.close(); if (socket != null) socket.close(); } } catch (Exception e) { e.printStackTrace(); } }
Note: When android Activity calls this method, it must open a sub-thread to call it (network access is a symbolic error in android in the main thread !!!!)
The following is the server code. Test to create a java class.
Public class extends er implements Runnable {public static void main (String [] args) {try {final ServerSocket server = new ServerSocket (3333); Thread th = new Thread (new Runnable () {public void run () {while (true) {try {System. out. println ("Start listening... "); Socket socket = server. accept (); System. out. println ("linked"); receiveFile (socket) ;}catch (Exception e) {}}}); th. run (); // start the thread to run} catch (Ex Ception e) {e. printStackTrace () ;}} public void run () {} public static void receiveFile (Socket socket) {byte [] inputByte = null; int length = 0; DataInputStream dis = null; fileOutputStream fos = null; try {dis = new DataInputStream (socket. getInputStream (); fos = new FileOutputStream (new File (". /cc.jpg "); inputByte = new byte [1024]; System. out. println ("start to receive data... "); while (length = di S. read (inputByte, 0, inputByte. length)> 0) {System. out. println (length); fos. write (inputByte, 0, length); fos. flush ();} System. out. println ("completed receiving");} finally {if (fos! = Null) fos. close (); if (dis! = Null) dis. close (); if (socket! = Null) socket. close () ;}} catch (Exception e ){}}}
Finally, you can check whether the program is successful in the root directory of the java project.