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

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();
}
}
}

Related

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.

Chat along with another data sending in socket programming android

I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}

I m not receiving real time stream because receivePacket is the most 1024 bytes

i want to do real time stream from my pc to android device with WIFI. Server code is written by Java. My codes is running true. when I clicked the button in android, in server, sendPacket is actived and it sends packet. I send 65000 bytes(sendPacket) from server, but client receive is 1024 bytes(receivePacket). that' s problem. If sendPacket is smaller, view is very bad.Thank you for your helps...
main.java(server)
public class main {
private static JFrame jframeImage;
private static FacePanel panelImage;
public static DatagramSocket socket;
private static ThreadSender threadSender;
public static void main(String[] args) {
try {
socket = new DatagramSocket(Constants.PORT_ADDRESS);
} catch (SocketException e) {
e.printStackTrace();
}
threadSender = new ThreadSender(socket);
threadSender.start();
initFrame();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camFeed = new VideoCapture(0);
Mat matCamFeed = new Mat();
Mat matSender = new Mat();
byte[] clientInformation = new byte[10];
DatagramPacket packetClientInf = null;
try {
System.out.println("Client Bekleniyor....");
packetClientInf = new DatagramPacket(clientInformation,
clientInformation.length);
socket.receive(packetClientInf);
System.out.println("Client baglandi.");
} catch (IOException e1) {
e1.printStackTrace();
}
Constants.IP_ADDRESS = packetClientInf.getAddress();
Constants.CLIENT_PORT = packetClientInf.getPort();
System.out.println("client ip:"+packetClientInf.getAddress());
System.out.println("client port: "+packetClientInf.getPort());
String s = new String(packetClientInf.getData());
System.out.println("gelen data: "+s);
while (true) {
camFeed.read(matCamFeed);
Imgproc.resize(matCamFeed, matSender, new Size(150, 150));
BufferedImage bufImage = null;
try {
bufImage = matToBufferedImage(matSender);
} catch (IOException e) {
e.printStackTrace();
}
threadSender.setBufImageForSend(bufImage);
threadSender.run();
panelImage.setImage(bufImage);
panelImage.repaint();
}
}
public static void initFrame() {
jframeImage = new JFrame("Image from client");
jframeImage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframeImage.setSize(400, 400);
jframeImage.setVisible(true);
JButton btnGonder = new JButton("gonder");
btnGonder.setVisible(true);
panelImage = new FacePanel();
jframeImage.setContentPane(panelImage);
}
public static BufferedImage matToBufferedImage(Mat mat) throws IOException {
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", mat, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
return img;
}
}
ThreadSender.java
public class ThreadSender extends Thread {
private BufferedImage bufImageForSend;
private DatagramSocket socket;
public ThreadSender(DatagramSocket socket) {
this.socket = socket;
bufImageForSend = null;
}
public void setBufImageForSend(BufferedImage bufImageForSend) {
this.bufImageForSend = bufImageForSend;
}
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
if (bufImageForSend != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(bufImageForSend, "jpeg", bos);
} catch (Exception e) {
// TODO: handle exception
}
byte[] byteImage = bos.toByteArray();
System.out.println("Total image byte length: " + byteImage.length);
if (byteImage.length <= 65500) {
DatagramPacket packet = new DatagramPacket(byteImage,
byteImage.length, Constants.IP_ADDRESS, Constants.CLIENT_PORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
}
Client.java
public class MainActivity extends ActionBarActivity {
EditText messageEdit;
Button sendButton;
TextView informationText;
ImageView image;
CheckBox devam;
int PORT=999;
InetAddress IPAddress;
String serverHostname = new String("172.28.8.44");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = (Button) findViewById(R.id.button1);
messageEdit = (EditText) findViewById(R.id.editText1);
image = (ImageView) findViewById(R.id.imageView1);
devam = (CheckBox) findViewById(R.id.checkbox);
try {
IPAddress = InetAddress.getByName(serverHostname);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramSocket clientSocket = null;
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sentence = messageEdit.getText()
.toString();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, IPAddress,
PORT);
try {
clientSocket.send(sendPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket receivePacket = new DatagramPacket(
receiveData, receiveData.length);
try {
clientSocket.receive(receivePacket);
byte[] b = receivePacket.getData();
ByteArrayInputStream ba=new ByteArrayInputStream(b);
BufferedInputStream bi=new BufferedInputStream(ba);
final Bitmap bitmap = BitmapFactory
.decodeStream(bi);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
image.setImageBitmap(bitmap);
image.invalidate();
}
});
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// TODO Auto-generated method stub
}
});
}
}

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.

Android - Send an image through socket programming

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.

Categories

Resources