Dgenoves Dgenoves - 4 months ago 9x
Android Question

Trying to make a server in Java that sends an image to my Android device using sockets

I'm trying to send an image using a Java server to my Android device but it doesn't work and I don't know why.

The code for the server is:

public class Main {

public static void main(String argv[]) throws Exception

ServerSocket welcomeSocket = new ServerSocket(6789);
Image image = null;

while(true) {

Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

ObjectOutputStream outToClient = new ObjectOutputStream(connectionSocket.getOutputStream());

File f = new File("/resources/image.png");
image = ImageIO.read(f);

outToClient.writeObject( new ImageIcon(""+image) );



I think the problem is in the server because the Android app works with another server


BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));

DataInputStream in;

BufferedInputStream buf;

DataInputStream mod ;

Socket sc = new Socket(myIP,48000);

DataInputStream infromServer = new DataInputStream(sc.getInputStream());

mod = infromServer;

Bitmap mPhotoPicture = BitmapFactory.decodeStream(modifiedSentence);



The other server is probably sending the raw image data (not an ImageIcon serialized object). It looks like BitmapFactory expects the image's raw bytes. Try writing the raw bytes out to your socket:

FileInputStream fis = null;
int size = (int)f.length();
byte[] bytes = new byte[size];
fis = new FileInputStream( f );
int read = fis.read( bytes );

connectionSocket.getOutputStream().write( bytes );

Obviously, you'll need to add some error detection and handling to make this robust.