Android - Send an image through socket programming - android

I am implementing a socket application where one phone will be a client and the other will be a server. The program is able to send strings using print writer just fine from the client to the sever but when i try to send an image file, it throws an exception. I'd really appreciate if someone could help me out.
Here is the code for the server
public class ServerActivity extends Activity {
private TextView serverStatus;
private ImageView profile;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
profile = (ImageView) findViewById(R.id.image);
String filepath = "/sdcard/DCIM/time table.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
profile.setImageBitmap(bm);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
//String line;
byte [] line;
Bitmap bitmap;
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
/*InputStream in = client.getInputStream();
line = null;
in.read(line);
Log.d("ServerActivity", line.toString());
bitmap = BitmapFactory.decodeByteArray(line , 0, line.length);*/
int bytesRead;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/IMG-20130112-WA0011.jpeg"); // destination path and name of file
//FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
handler.post(new Runnable() {
#Override
public void run() {
profile.setImageBitmap(bitmap);
//serverStatus.setText(line);
}
});
/*BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText(line);
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
}
});
}*/
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the client side code
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
private ImageView profile;
private byte [] imgbyte;
String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
profile = (ImageView) findViewById(R.id.imageView1);
filepath = "/sdcard/small.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
imgbyte = getBytesFromBitmap(bm);
profile.setImageBitmap(bm);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
/*File myFile = new File (filepath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
Log.d("ClientActivity", "C: Sending command.");
//System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();*/
Log.d("ClientActivity", "C: Sending command.");
/*PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);*/
// WHERE YOU ISSUE THE COMMANDS
OutputStream output = socket.getOutputStream();
Log.d("ClientActivity", "C: image writing.");
output.write(imgbyte);
output.flush();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
}
update:
The exception is thrown at the server side code. Its the exception which reads :"Oops. Connection interrupted. Please reconnect your phones."
This is the exception that is thrown:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

Thanks everyone , I found the error.
The toast messages have to be inside the UI thread or the handler . As I had a few of them in a non UI thread, it began to throw the exception.

Related

Send an image through socket: ByteArrayOutputStream.size() return negative value (sometimes )

I am making server-client program, the server is Java on the computer and the client is android app (android studio) and I try to send image from the server to the client, and to show this image on the client's screen by ImageView. The problem is that sometimes its work and sometimes it doesn't work. Looks like there are times that ByteArrayOutputStream.size() return negative value in the client side in the variable len (that keep the length). When the return value is positive it works. Why am I getting negative values (sometimes)?
Server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println("IMAGE");
sendImage(new File("ssss.PNG"));
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client code(android):
public class MainActivity extends AppCompatActivity {
public Socket socket;
public PrintWriter out;
public Scanner in;
public TextView textView;
public DataOutputStream dos=null;
public DataInputStream dis=null;
public ImageView imageView;
public Bitmap bitmap;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.text);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(TAG, "connected1234");
while (in.hasNextLine()) {
String response = in.nextLine();
if (response.startsWith("IMAGE")) {
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
byte[] data;
int len= input.readInt();
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The error:
len: -298696669
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.sendimageexample, PID: 17224
java.lang.NegativeArraySizeException: -298696669
at com.example.sendimageexample.MainActivity$ClientThread.run(MainActivity.java:80)
at java.lang.Thread.run(Thread.java:784)`
I solved it!
client code:
public class MainActivity extends AppCompatActivity {
public Socket socket;
public ImageView imageView;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(TAG, "Adder: "+serverAddr);
socket = new Socket(serverAddr, SERVERPORT);
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
Log.d(TAG, "connected1234");
byte[] data;
int len= input.readInt();//-298696669//17976
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data
.length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
ByteArrayOutputStream bos =new ByteArrayOutputStream();
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.image22);
Log.d(TAG, "bitmap1: "+bitmap1);
bitmap1.compress(Bitmap.CompressFormat.PNG,0,bos);
byte []array=bos.toByteArray();
OutputStream outputStream=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(outputStream);
dos.writeInt(bos.size());
dos.write(array,0,array.length);
Log.d(TAG, "bos.size: "+bos.size());
Log.d(TAG, "bos.array: "+bos.toByteArray());
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
Server jframe=this;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
//this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sendImage(new File("ssss.PNG"));
InputStream inputStream;
try {
inputStream = socket.getInputStream();
DataInputStream dis=new DataInputStream(inputStream);
int size = dis.readInt();
System.out.println("size: "+size);
byte[] imageAr = new byte[size];
dis.readFully(imageAr);
System.out.println("imageAr: "+imageAr);
System.out.println("dis: "+dis);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
jframe.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
revalidate();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
System.out.println("read: "+read);
System.out.println("buf: "+buf);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
System.out.println("ao.toByteArray(): "+ao.toByteArray());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to send An Image Using Socket programming in android (client to local server) [duplicate]

I am implementing a socket application where one phone will be a client and the other will be a server. The program is able to send strings using print writer just fine from the client to the sever but when i try to send an image file, it throws an exception. I'd really appreciate if someone could help me out.
Here is the code for the server
public class ServerActivity extends Activity {
private TextView serverStatus;
private ImageView profile;
// DEFAULT IP
public static String SERVERIP = "10.0.2.15";
// DESIGNATE A PORT
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
profile = (ImageView) findViewById(R.id.image);
String filepath = "/sdcard/DCIM/time table.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
profile.setImageBitmap(bm);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
//String line;
byte [] line;
Bitmap bitmap;
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// LISTEN FOR INCOMING CLIENTS
Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
/*InputStream in = client.getInputStream();
line = null;
in.read(line);
Log.d("ServerActivity", line.toString());
bitmap = BitmapFactory.decodeByteArray(line , 0, line.length);*/
int bytesRead;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
InputStream is = client.getInputStream();
FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/IMG-20130112-WA0011.jpeg"); // destination path and name of file
//FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
handler.post(new Runnable() {
#Override
public void run() {
profile.setImageBitmap(bitmap);
//serverStatus.setText(line);
}
});
/*BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText(line);
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
}
});
}*/
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// GETS THE IP ADDRESS OF YOUR PHONE'S NETWORK
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the client side code
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
private ImageView profile;
private byte [] imgbyte;
String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
profile = (ImageView) findViewById(R.id.imageView1);
filepath = "/sdcard/small.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
imgbyte = getBytesFromBitmap(bm);
profile.setImageBitmap(bm);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
while (connected) {
try {
/*File myFile = new File (filepath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
Log.d("ClientActivity", "C: Sending command.");
//System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();*/
Log.d("ClientActivity", "C: Sending command.");
/*PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);*/
// WHERE YOU ISSUE THE COMMANDS
OutputStream output = socket.getOutputStream();
Log.d("ClientActivity", "C: image writing.");
output.write(imgbyte);
output.flush();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
}
update:
The exception is thrown at the server side code. Its the exception which reads :"Oops. Connection interrupted. Please reconnect your phones."
This is the exception that is thrown:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Thanks everyone , I found the error.
The toast messages have to be inside the UI thread or the handler . As I had a few of them in a non UI thread, it began to throw the exception.

Android socket does not receive all the bytes of an image [duplicate]

This question already has answers here:
Android: Image received over socket is corrupted
(2 answers)
Closed 8 years ago.
Hi I'm having problem receiving an image
In the last while it simply doesn't receive all the bytes and the program does not exit the while condition. With a 77970 bytes image, this receives 61592 bytes then just does nothing. It keeps stuck in the while. I dunno what to do, thanks for any help.
public class FileActivity extends Activity {
private EditText serverIp, getPort, exT;
private Button connectPhones;
private TextView tv, tvIP;
private Boolean connected = false;
private String serverIpAddress, portStr,ex;
private Socket socket;
private int port, len;
private String filepath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
exT = (EditText) findViewById(R.id.editText1);
tvIP = (TextView) findViewById(R.id.IPtv);
tv = (TextView) findViewById(R.id.Portatv);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
getPort = (EditText) findViewById(R.id.server_port);
}
public void connectListener(View v)
{
tv.setVisibility(View.GONE);
connectPhones.setVisibility(View.GONE);
getPort.setVisibility(View.GONE);
serverIp.setVisibility(View.GONE);
tvIP.setTextSize(16f);
tvIP.setText("Connesso");
exT.setVisibility(View.GONE);
ex = exT.getText().toString();
if (!connected) {
serverIpAddress = serverIp.getText().toString();
portStr = getPort.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
public class ClientThread implements Runnable
{
#Override
public void run() {
// TODO Auto-generated method stub
port = Integer.parseInt(portStr);
socket = new Socket();
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connessione in corso...");
socket = new Socket(serverAddr, port);
Log.d("ClientActivity", "C: Connesso!");
connected = true;
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
int bytes;
byte[] b = new byte[32];
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String l = in.readLine();
//String line = Integer.toString(l);
Log.d("PROVA", l);
try
{
len = Integer.parseInt(l); Log.d("CLIENT", Integer.toString(len));
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
byte[] img = new byte[1024]; //1082922
FileOutputStream fos = new FileOutputStream("/sdcard/" + ex);
BufferedOutputStream bos = new BufferedOutputStream(fos);
/*bytes = dis.read(img, 0, img.length);
bos.write(img, 0, img.length);*/
int count = 0;
while ((bytes = dis.read(img)) != -1) {
count += bytes;
Log.d("CLIENT", Integer.toString(count));
Log.d("TEST", Integer.toString(bytes));
//Write to file
bos.write(img, 0, bytes);
}
//bos.flush();
//bos.close();
Log.d("TCP", "Save to file");
} catch(IOException e){
e.printStackTrace();
}
} catch (Exception e) {
Log.e("ClientActivity", "C: Errore", e);
connected = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
if(connected == true)
{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server:
public class FileActivity extends Activity {
private String test;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private byte [] mybytearray;
private String tmp = null;
private TextView tv;
private File myFile;
private int l;
private String path;
private EditText editText;
private ServerSocket serverSocket;
private Socket client;
public static String SERVERIP = "10.0.2.15";
private final int SERVERPORT = 8080;
private byte [] imgbyte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
tv = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
SERVERIP = getLocalIpAddress();
Thread sThread = new Thread(new ServerThread());
sThread.start();
}
public void sendListener(View v) {
tmp = editText.getText().toString();
path = "/sdcard/" + tmp;
myFile = new File(path);Log.d("SERVER", "WORKS");
if(myFile.exists())
{
l = (int) myFile.length();Log.d("SERVER", "WORKS");
tv.setText(path + " Size:" + Integer.toString(l));
tmp = Integer.toString(l); Log.d("SERVER", "WORKS");
test = tmp;
Thread t = new Thread(new sSend());
t.start();
}
else
{
tv.setText("Il file non esiste");
}
}
public class sSend implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
out.println(test);
//out.close();
Log.d("SERVER", "WORKS");
byte[] mybytearray = new byte[1024]; //create a byte array to file
Log.d("SERVER", "WORKS");
fileInputStream = new FileInputStream(myFile);
bufferedInputStream = new BufferedInputStream(fileInputStream);
Log.d("SERVER", "WORKS");
//bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
Log.d("SERVER", "WORKS");
try{
outputStream = client.getOutputStream();
} catch(Exception e)
{
Log.d("OUTPUT", "UFFFF");
e.printStackTrace();
}
Log.d("SERVER", "WORKS");
int count = 0;
int size = 0;
while((count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length)) != -1)
{
// count = bufferedInputStream.read(mybytearray, 0 , mybytearray.length);
size += count;
Log.d("SERVER", "SEND");
try{
outputStream.write(mybytearray, 0, count);
} catch(Exception e) {
e.printStackTrace();
}
Log.d("TEST", Integer.toString(count));
}
Log.d("SERVER", "DONE");
Log.d("SERVER", Integer.toString(size));
}catch(Exception e){
e.printStackTrace();
}
}
}
public class ServerThread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(SERVERPORT);
client = serverSocket.accept();
//outputStream = client.getOutputStream();
Log.d("SERVER", "Connesso");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("TEST", "UFFFAAA");
}
}
}
private String getLocalIpAddress() {
String tmp = "";
int i = 0;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress())
{
tmp += "IP: " + inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return tmp;
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This looks like a repost. Why did you start a new thread? The other one was not ready yet. We had discovered some problems and you do not even mention them here. OP tries to send file size first and then the content. Also the client should read the file size first but it is a complete mess.

How to transfer bitmap using TCP socket

I have the a Server/Client application in which i want to send and display screenshot of server on client. Can any body help me in that. thanks
The code is the following
Server side
public class ServerActivity extends Activity {
private TextView serverStatus;
RelativeLayout mainLayout;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected");
mainLayout = (RelativeLayout)findViewById(R.id.screen);
ImageView iv =(ImageView)findViewById(R.id.iv);
File root = Environment.getExternalStorageDirectory();
File file = new File(root,"androidlife.jpg");
Bitmap b = Bitmap.createBitmap(mainLayout.getWidth(), mainLayout
.getHeight(), Bitmap.Config.ARGB_8888);
iv.setImageBitmap(b);
Canvas c = new Canvas(b);
mainLayout.draw(c);
//serverStatus.setText("Screenshot is displaying");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.i("TcpServer", "received: " + incomingMsg);
serverStatus.setText("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + SERVERPORT + System.getProperty("line.separator");
out.write(outgoingMsg);
//out.flush();
Log.i("TcpServer", "sent: " + outgoingMsg);
serverStatus.setText("sent: " + outgoingMsg);
//while ((line = in.readLine()) != null)
handler.post(new Runnable() {
#Override
public void run() {
}
});
// }
break;
}
catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client side code is:
public class ClientActivity extends Activity {
public EditText serverIp;
public TextView tv;
private Button connectPhones;
private String serverIpAddress = "";
private static final int SERVERPORT = 8080;
private boolean connected = false;
//private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
// if(true)
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
connected = true;
while (connected) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//send output msg
String outMsg = "TCP connecting to " + SERVERPORT + System.getProperty("line.separator");
out.write(outMsg);
out.flush();
Log.i("TcpClient", "sent: " + outMsg);
//accept server response
String inMsg = in.readLine() + System.getProperty("line.separator");
tv.setText("message from server"+ inMsg);
Log.i("TcpClient", "received: " + inMsg);
// ImageView iv = (ImageView)findViewById(R.id.iv);
// iv.setImageBitmap(bm);
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
I don't see in your code where where you are trying to send the Bitmap of image or screen shot!! and you cannot send send a Bitmap over socket you should add this in the sender side after creating the bitmap b to create a byte array out of the bitmap:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
In the server side receiver the bytearray and then recreat the bitmap in this way:
Bitmap breceived = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

android socket file transfer

Need help... I have understood how to make server-client socket conection... It works fie... Now I want to transfer files from server to client and back.... here are my sources...
Socket server...
public class ServerActivity extends Activity {
private TextView serverStatus;
// default ip
public static String SERVERIP = "192.168.1.1";
// designate a port
public static final int SERVERPORT = 8080;
private Handler handler = new Handler();
private ServerSocket serverSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
}
public class ServerThread implements Runnable {
public void run() {
try {
if (SERVERIP != null) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Listening on IP: " + SERVERIP);
}
});
serverSocket = new ServerSocket(SERVERPORT);
while (true) {
// listen for incoming clients
Socket client = serverSocket.accept();
/////////////////////////////////
File myFile = new File ("/sdcard/frostwire.apk");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = client.getOutputStream();
System.out.println("Sending...");
serverStatus.setText("sending 123.exe...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
client.close();
////////////////////////////
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Connected.");
}
});
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
handler.post(new Runnable() {
#Override
public void run() {
// do whatever you want to the front end
// this is where you can be creative
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} else {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Couldn't detect internet connection.");
}
});
}
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
serverStatus.setText("Error");
}
});
e.printStackTrace();
}
}
}
// gets the ip address of your phone's network
private String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); }
}
}
} catch (SocketException ex) {
Log.e("ServerActivity", ex.toString());
}
return null;
}
#Override
protected void onStop() {
super.onStop();
try {
// make sure you close the socket upon exiting
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Socket Client...
public class ClientActivity extends Activity {
private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "";
private boolean connected = false;
private Handler handler = new Handler();
int filesize; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
serverIp = (EditText) findViewById(R.id.server_ip);
connectPhones = (Button) findViewById(R.id.connect_phones);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, ServerActivity.SERVERPORT);
connected = true;
////////// // receive file
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("/sdcard/frostwire.apk");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
socket.close();
//////////////////////////////
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
// where you issue the commands
out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Pieces of source which are marked by "///////" don't work.... Help
Better you replace the following your code
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
with the following one
do {
bytesRead =is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead > 0)
{
current += bytesRead;
}
} while(bytesRead > 0);
Then try it
after going through above discussion i would like to add few comments-
Have you added permission code for reading sdcard in android manifest file ? If not you should add following code as the server is accessing External Storage. Do for the client also to write in external storage.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Else, the directory you have provided is not correct. Check the directory.
In the client program, you have defined file_size which is not assigned any value nowhere in the program.
I would also like to suggest that, the file_size in the client program should be greater than the file to be transfer and size is in byte.

Categories

Resources