user2370241
user2370241

Reputation:

send image from android java to c# server on pc

i'm trying to send image from android to C# server using Socket, but something goes wrong.

package com.example.clientsocket;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        serverMessage=(TextView)findViewById(R.id.textView1);
    }
public void Start(View view)
{
    m_objThreadClient=new Thread(new Runnable() 
    {
          public void run()
           {
              try 
               {
                 clientSocket= new Socket("192.168.88.113",2001);
                 //ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());



                 File myFile = new File("/storage/sdcard0/Pictures/CameraSample/*.jpg");
                 InputStream fis = new FileInputStream("/storage/sdcard0/Pictures/CameraSample/*.jpg");

                 byte [] buffer = new byte[(int)myFile.length()];
                 fis.read(buffer,0,buffer.length);


                OutputStream outputStream = clientSocket.getOutputStream();
                outputStream.write(buffer.length);
                outputStream.write(buffer,0,buffer.length);
                 outputStream.flush();
                 outputStream.close();
                 clientSocket.close();
                 //byte [] buffer = new byte[(int)myFile.length()];




              // ...
              //fis.read(buffer,0,buffer.length);
              //OutputStream os = clientSocket.getOutputStream();
              //oos.writeObject("37");
              //oos.flush();
              //oos.writeObject(buffer);
              //os.write(37);
              //os.write(buffer);
              // <- This one.
                /* 
                 int temp = 0 ;  
                 while((temp = fis.read(buffer)) != -1)
                 {  
                     outputStream.write(buffer, 0, temp);  
                 }  */




                 /*
                 Message serverMessage= Message.obtain();
                 ObjectInputStream ois =new ObjectInputStream(clientSocket.getInputStream());
                 String strMessage = (String)ois.readObject();
                serverMessage.obj=strMessage;
                mHandler.sendMessage(serverMessage); 
                oos.close();
                ois.close();*/
               } 
               catch (Exception e) 
               {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }
            });

     m_objThreadClient.start();

}
Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) 
    {
        messageDisplay(msg.obj.toString());
    }
};
public void messageDisplay(String servermessage)
{
    serverMessage.setText(""+servermessage);
}

}

Server gets 60800 as buffer length every single image that I send, and I can't make an image on C# using this array. I want than to receive char array from server on android. Am I doing something wrong in the JPG file, because I want to have only one image at the same time in my folder?

Upvotes: 1

Views: 1643

Answers (2)

Garra San
Garra San

Reputation: 1

This is my sample C# client socket send image to Android Server. In my sending side, I send Image size first and follow by image bytes. Hope it helps.

C# Client

 try
        {

            //   IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.173.129");
            IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.1.32");
            IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 4800);

           string file=@"C:\Users\test\Desktop\send image\test\abc.jpg
            {
                // Create Socket to send

                Socket senderSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                senderSocket.Connect(ipEnd);
                //send picture name



                // Connect the socket to the remote endpoint. Catch any errors.
                FileInfo FileInfo = new FileInfo(file);
                byte[] data = new byte[8];
                String fInfoStr = FileInfo.Length.ToString();
                while (fInfoStr.Length < 8)
                {
                    fInfoStr = "0" + fInfoStr;
                }
                byte[] countBuf = Encoding.ASCII.GetBytes(fInfoStr);

                byte[] fBuffer = new byte[FileInfo.Length];
                //FileStream
                FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                //Read byte from image
                fs.Read(fBuffer, 0, fBuffer.Length);
                fs.Flush();
                fs.Close();

                senderSocket.Send(fBuffer, 0, fBuffer.Length, SocketFlags.None);
                senderSocket.Close();
                lblTestMsg.Visible = true;
                lblErrorMsg.Visible = false;
                lblTestMsg.Text = "File Sent Successfully"; 
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);            
        }

Android Server

                Socket socket = serverSocket.accept();
                InputStream iStream = socket.getInputStream();                 ;
                String currentDateandTime = sdf.format(new Date());



                //   int filenamelen =iStream.read();

                //image Name
                byte[] countBuf = new byte[8];
                //  byte[] imageNameByte = new byte[7];
                iStream.read(countBuf);
                //iStream.read(imageNameByte,0,7);
                readTxt = new String(countBuf);
                // imageName= new String(imageNameByte);
                int size = Integer.parseInt(readTxt);


                //Send byte array                                      
                 senderSocket.Send(countBuf, 0, data.Length, SocketFlags.None);new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName).mkdirs();
                Log.e("TCP", "Create Drkt");
                //Create Image(File)

                new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName, imageName + ".jpg").createNewFile();
                Log.e("TCP", "Create Img");

                try {
                    FileOutputStream fOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName + File.separator + imageName + ".jpg");
                    BufferedOutputStream BufOutputStream = new BufferedOutputStream(fOutputStream);
                    byte[] aByte = new byte[size];
                    int byteRead;
                    //   int bytesRead = iStream.read(aByte);
                    //Read from server
                    while ((byteRead = iStream.read(aByte)) > 0) {
                        Log.e("TCP", "Save to file");//Write to file
                        BufOutputStream.write(aByte, 0, byteRead);
                    }
                    publishProgress();
                    notifyID++;
                    // String imageUri =Environment.getExternalStorageDirectory() + File.separator + "myDirectory" + File.separator + readTxt + File.separator+currentDateandTime+".jpg";
                    BufOutputStream.flush();
                    BufOutputStream.close();
                    socket.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
        }

Upvotes: 0

Ilya Gazman
Ilya Gazman

Reputation: 32271

You have a mistake in this code:

byte [] buffer = new byte[(int)myFile.length()];
fis.read(buffer,0,buffer.length);

OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(buffer.length); // You are changing the image here...
outputStream.write(buffer,0,buffer.length);

You are sending wrong data on the Socket, and you may run on out of memory if image is to big. Also you are converting myFile.length() to int. There is a reason for files length to be long. It allow very large files to be scanned. May be it doesn't meter in your case but I suggest not doing this.

It should be some thing like this:

byte [] buffer = new byte[1048];
OutputStream outputStream = clientSocket.getOutputStream();

int numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);

while(numberOfBytesBeenRead != -1){
    outputStream.write(buffer,0,numberOfBytesBeenRead);
    numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);
}    

Upvotes: 0

Related Questions