Android send image over socket, received blank image - java

im trying to send image over socket in android using two emulator, log file give me
05-28 13:55:07.349: I/System.out(26763): Receiving...
and i can see the created image from file explorer in data\files\output.jpg but it's blank and it's size =0k
package com.javacodegeeks.android.androidsocketserver;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
public class Main extends Activity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStream inputStream;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
private static int bufferSize = 3000; // bufferSize temporary hardcoded
private static int bytesRead;
private static int totalbytesRead = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
init();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void init() throws IOException {
// TODO Auto-generated method stub
serverSocket = new ServerSocket(6000); // Server socket
System.out.println("Server started. Listening to the port 4444");
clientSocket = serverSocket.accept();
byte[] data = new byte[bufferSize]; // create byte array to buffer the
// file
inputStream = clientSocket.getInputStream();
String filePath = this.getFilesDir().getPath().toString()
+ "/output.jpg";
fileOutputStream = new FileOutputStream(filePath);
// fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
System.out.println("Receiving...");
// following lines read the input slide file byte by byte
bytesRead = inputStream.read(data,0,data.length);
totalbytesRead = bytesRead;
do {
bytesRead =
inputStream.read(data, totalbytesRead, (data.length-totalbytesRead));
if(bytesRead >= 0) totalbytesRead += bytesRead;
} while(bytesRead > -1);
bufferedOutputStream.write(data, 0 , totalbytesRead);
bufferedOutputStream.flush();
long end = System.currentTimeMillis();
System.out.println(end);
bufferedOutputStream.close();
System.out.println("Sever recieved the file");
}
}
and this is client side
package com.javacodegeeks.android.androidsocketclient;
/*
* This is a simple Android mobile client
* This application send any file to a remort server when the
* send button is pressed
* Author by Lak J Comspace
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Transfer extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
button = (Button) findViewById(R.id.button1); // reference to the send
// button
text = (TextView) findViewById(R.id.textView1); // reference to the text
// view
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
File file = new File("Desktop:\\test.jpg"); // create file
// instance
client = new Socket("10.0.2.2", 5000);
byte[] mybytearray = new byte[(int) file.length()]; // create
// a
// byte
// array
// to
// file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(
fileInputStream);
outputStream = client.getOutputStream();
int read_count = 0;
while ((read_count = bufferedInputStream.read(mybytearray,
0, mybytearray.length)) != -1) {
outputStream.write(mybytearray, 0, read_count); // Now
// writes
// the
// correct
// amount
// of
// bytes
outputStream.flush();
}
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

Remove the first inputStream.read() as there you read the whole filecontents already but throw it away. There is nothing more to read the second time.

Related

JAVA TCP Server Error

Server : package Server;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen(){
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true){
if((image = ImageIO.read(min)) != null){
while(min.read() != 'y');
System.out.println("received");
mout.write('y');
mout.flush();
Main.drawImage(image);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client :package Client;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] buffer = new byte[10];
while(true){
ImageIO.write(webcam.getImage(), "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This Program works well about 10sec. But after that It doesn't work. Socket is Connected but It doesn't send anything. I guess it doesn't match sync, so I match sync, but it's not work too. I don't have an idea. why It doesn't work. please help. I can't find problem
Your client needs to send the size of transfered image to server prior to sending the image itself, because your server needs to know how long the image is, in order to read it from socket and start receiving the char data coming right after the image.
And since "ImageIO" has no means of specifying the number of bytes supposed to be read from the input stream, you should use InputStream instead.
See the modified code below (I put comments whenever added a new line, everything else is identical with yours):
Server:
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; //<--- added
import java.io.DataInputStream; //<--- added
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
private DataInputStream din; //<--- added DataInputStream
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
din = new DataInputStream(min); //<--- initialized DataInputStream
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen()
{
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true)
{
int arrlen = din.readInt(); //<--- receive image size in order to prepare a buffer for it
byte[] b = new byte[arrlen]; //<--- prepare a buffer
din.readFully(b); //<--- receive image data
while(min.read() != 'y');
mout.write('y');
mout.flush();
InputStream bais = new ByteArrayInputStream(b); //<--- get ByteArrayInputStream from buffer
BufferedImage image = ImageIO.read(bais); //<--- prepare BufferedImage from ByteArrayInputStream
bais.close(); //<--- close ByteArrayInputStream
Main.drawImage(image);
}//end while true
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client:
import java.awt.image.BufferedImage; //<--- added
import java.io.ByteArrayOutputStream; //<--- added
import java.io.DataOutputStream; //<--- added
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
DataOutputStream dos = new DataOutputStream(out); //<--- added DataOutputStream
BufferedImage image = null; //<--- added BufferedImage to keep image from webcam
while(true){
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //<--- create ByteArrayOutputStream
image = webcam.getImage(); //<--- get BufferedImage from webcam
ImageIO.write(image, "png", baos); //<--- write image into ByteArrayOutputStream
dos.writeInt(baos.size()); //<--- send image size
dos.flush(); //<--- flush DataOutputStream
baos.close(); //<--- close ByteArrayOutputStream
ImageIO.write(image, "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Can't set ImageView photo from datainputstream JavaFx socket application

I am trying to output an image to an ImageView in javafx, i am recieving the image via socket connection and saving it to my hard-drive then i create an Image object with the path of the newly created image, the problem is that the image view is not updated.
public void save(String path, DataInputStream dis) throws IOException {
FileOutputStream fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
//Image imBuff = ImageIO.read(socket.getInputStream());
int filesize = dis.readInt(); // Send file size in separate msg
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("img"+frame_number+".jpg");
File f = new File("img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
}catch(Exception e){
System.out.println("didn't find");
}
System.out.println("stream size:"+image_Stream.size());
ps.println("ok");
frame_number++;
}
Things i have tried:
1- i tried to used the path i saved the photo in to create an Image then used the setImage() function on my ImageView (iv), i got Invalid Url even though i loaded an image image from the same directory before.
2- we tried using (file:///) to get an absolute path but it didn't work, also invalid url
3- i tried loading the image as a file first then using the toURI() function to get the proper path to it then create an image accordingly, i don't get an error but it also doesn't update the UI
P.S
this function is called in a sub Thread that updates an ImageView in the main javafx thread, i tried it with images not loaded through the socket connection and it worked, but when i try to display the images i receive the face this problem.
EDIT: I managed to load the image properly, now i can't update the ImageView using iv.setImage()
EDIT:
CameraOBJ class
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.util.Duration;
public class CameraOBJ implements Runnable{
String name;
int delay;
Socket socket;
String ip;
int port;
PrintStream ps;
Scanner sc;
static int frame_number;
StackPane sp;
Label delay_lbl;
ImageView iv;
public CameraOBJ (String name, String ip, int port){
this.ip = ip;
this.port = port;
this.name = name;
sp = new StackPane();
}
public void run() {
setStackPane();
connect();
while(true){
update();
}
// Timeline timeline = new Timeline();
// Duration duration = Duration.seconds(1/Settings.FPS);
// KeyFrame f1 = new KeyFrame(duration,e->{
// update();
// });
// timeline.getKeyFrames().add(f1);
// timeline.setCycleCount(Timeline.INDEFINITE);
// timeline.play();
}
private void update() {
// Platform.runLater(new Runnable() {
// public void run() {
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
if(dis!=null){
save("images",dis);
//setStackPane();
}
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
// }
// });
}
public void setStackPane(){
Platform.runLater(new Runnable() {
public void run() {
sp.setMinSize(500, 384);
sp.setMaxSize(500, 384);
sp.setStyle("-fx-background-color: #FFFFFF;");
Image image = new Image("Camera_Frame.jpg");
iv = new ImageView(image);
iv.setFitWidth(470);
iv.setPreserveRatio(true);
Label name_lbl = new Label(name);
delay_lbl = new Label(delay+"");
sp.setAlignment(iv,Pos.CENTER);
sp.setAlignment(name_lbl,Pos.TOP_LEFT);
sp.setAlignment(delay_lbl,Pos.BOTTOM_RIGHT);
sp.getChildren().addAll(iv,name_lbl,delay_lbl);
}
});
}
public void connect(){
try{
socket = new Socket(ip, port);
System.out.println(socket.isConnected());
ps = new PrintStream(socket.getOutputStream());
sc = new Scanner(socket.getInputStream());
}
catch (Exception c){
c.getMessage();
}
}
public void save(String path, DataInputStream dis) throws IOException {
Platform.runLater(new Runnable() {
public void run() {
FileOutputStream fos;
try {
fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
int filesize;
try {
filesize = dis.readInt();
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("file:img"+frame_number+".jpg");
File f = new File("C:\\Users\\ahmed\\workspace\\College\\RTS_Client\\src\\img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
delay_lbl.setText("frame_number: "+frame_number);
}catch(Exception e){
System.out.println("didn't find");
}
frame_number++;
}
});
}
}
Main class:
import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import com.sun.prism.paint.Color;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class main extends Application{
static Stage window;
static String default_ip = "192.168.43.200";
static int default_port = 1234;
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
window = stage;
window.setResizable(false);
window.setTitle("Control Room");
StackPane sp = new StackPane();
sp.setMinSize(500, 500);
Scene sc = new Scene(sp);
window.setScene(sc);
window.show();
CameraOBJ camera = new CameraOBJ("Camera 1", default_ip, default_port);
Thread t = new Thread(camera);
camera.run();
sc = new Scene(camera.sp);
window.setScene(sc);
}
}
Server class:
import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Camera implements Runnable {
long timeStamp;
int delayShift;
int FPS;
boolean idle;
//Control Rooms object here
int portNumber;
Socket csocket;
Camera() {
}
Camera(Socket csocket) {
this.csocket = csocket;
}
void startConnection() throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Camera(sock)).start();
}
}
public void run() {//Start Stream
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
Scanner inpstream = new Scanner(csocket.getInputStream());
// Receiving an integer that is sent from the client side.
int ID = inpstream.nextInt();
// Generating a reply based on the ID sent from the client.
String response = "";
if (ID == 1100) {
response = "Your name is Mahmoud. \n" + "You are 22 years old.";
} else {
response = "No data found matching the ID you entered.";
}
// Sending the reply through the OutputStream to the client.
pstream.println(response);
pstream.close();
terminateConnection();
} catch (InputMismatchException e) {
System.out.println(e.toString() + "\nNo data is received.");
} catch (IOException e) {
System.out.println(e.toString());
} catch (Exception c) {
System.out.println(c.toString());
}
}
void terminateConnection() throws IOException {
csocket.close();
}
public static void main(String[] args) throws Exception {
Camera cam = new Camera();
cam.startConnection();
}
}

Sending Multiple Files Via Socket using ObjectOutputStream

I'm creating an application which I have to send multiple images one after another and I use Object(Output/Input)Stream inside of a while loop. But It only send one file I guess its the first image. Can I send multiple files with Object(Output/Input)Stream? If so, What's the issue with my code?
Server : (Sends Screenshots from PC )
package application;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ScreenCapture {
Socket socket;
ObjectOutputStream os;
Robot robot;
PrintStream ps;
public ScreenCapture() throws IOException, AWTException {
// TODO Auto-generated constructor stub
socket = SocketWrapper.getSocket();
os = new ObjectOutputStream(socket.getOutputStream());
robot = new Robot();
ps = new PrintStream(socket.getOutputStream());
new Record().start();
}
private class Record extends Thread{
#Override
public void run() {
while(true){
getScreenShot();
FileInputStream fis;
try {
File f = new File("/Users/Tomahawk/Documents/send.jpg");
fis = new FileInputStream(f);
byte[] byteArray = new byte[fis.available()];
fis.read(byteArray);
os.writeObject(byteArray);
os.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Sent File");
}
}
}
public void getScreenShot(){
Rectangle rect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage img = robot.createScreenCapture(rect);
try {
ImageIO.write(img, "jpg", new File("/Users/Tomahawk/Documents/send.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client : (Receives Screenshots and save It on the phone)
package com.pcontrol.tomahawk.pcontrol;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ScreenCapture extends Activity {
Socket socket;
ObjectInputStream is;
OutputStream os;
Scanner scanner;
ImageView screenCap;
int filesize = 0;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_capture);
socket = SocketWrapper.getSocket();
screenCap = (ImageView) findViewById(R.id.screenCap);
new ReceiveFiles().execute();
}
private class ReceiveFiles extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
while(true) {
try {
is = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
os = new FileOutputStream("/sdcard/"+i+".jpg");
byte[] sentArray = (byte[]) is.readObject();
os.write(sentArray);
os.flush();
publishProgress();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onProgressUpdate(Void... values) {
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/"+i+".jpg");
screenCap.setImageBitmap(bmp);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_screen_capture, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
That endless loop is not so endless -- in fact, it will not even loop once.
You have a "return null" at the end of your "while(true)" block. After the first iteration, your method will return.

Android tcp client connects then disconnect from java server

I am doing java server on my pc and having my android device connect to it. I can connect it but it disconnects as soon as it connects. I am sure there is something I need to do on the android side but I am little lost on it. I have the internet permission so that is fine.
Also ignore the commented code I was sending image from my android to pc. Also ignore the savebitmap and take screenshot I don't think its affecting the connection if its not being called.
Java Server:
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*; //access JFrame
import javax.swing.text.html.HTMLDocument.Iterator;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
public class tcpmain {
BufferedReader in;
static final int PORT = 9000;
public static void main(String[] args) {
// TODO Auto-generated method stub
//lines to make the gui frame
JFrame mainframe = new JFrame();
mainframe.setTitle("TCP Listener");
mainframe.setSize(600,800);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setVisible(true);
ServerSocket serverSocket = null;
Socket socket = null;
try{
serverSocket = new ServerSocket(PORT);
//Receive code
/*int filesize=450660;
int bytesRead;
int current=0;
//receive file
byte [] mybytearray = new byte [filesize];
InputStream is = srsvsock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Andy\\Desktop\\testimage.jpg");
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();*/
}
catch(Exception e){
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "Client connected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new threa for a client
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
client handler for java server
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket){
this.socket = clientSocket;
}
public void run(){
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try{
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
}catch(Exception e){
return;
}
String line;
while(true){
try{
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")){
socket.close();
return;
}else{
out.writeBytes(line+ "\n\r");
out.flush();
}
}catch(Exception e){
e.printStackTrace();
return;
}
}
}
}
Here is android client:
package com.example.tcpsocket;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 9000;
private static final String SERVER_IP = "192.168.1.113";
Bitmap bitmap;
File imagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnconnect = (Button)findViewById(R.id.button1);
btnconnect.setOnClickListener(connect);
}
private OnClickListener connect = new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Bitmap bitmap = takeScreenshot();
// saveBitmap(bitmap);
new Thread(new clienthread()).start();
}
};
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap){
File imagePath = new File("sdcard/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
new Thread(new clienthread()).start();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class clienthread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
/*File imagePath = new File("sdcard/screenshot.jpg");
byte[] mybytearray = new byte[450560];
FileInputStream fis = new FileInputStream(imagePath);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.close();*/
}
catch(Exception e){
}
}
}
}
Here:
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();//Don't do this here!!!!!!
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You shouldn't close your socket after you started your Thread. The closing of the socket should be the job of the EchoThread after you finished communicating with it. You can insert this line at the end of run() method socket.close(); so it closes itself when you're done.
Looks like it is most likely due to this line:
if ( socket != null && !socket.isClosed() ){
If your socket was previously opened and you passed if off to the thread to handle, the socket would still be open and socket.isClosed() will return false and you'll immediately close the socket and clean it up in your main thread.

Android Client/Server Socket client not receiving

I am at this with ages and the problem i am having is simple i am not able to print out the data from the server to client everything else is working just that when the server sends a message to the client the phone it never gets or prints it out any insight or help would be great and i am getting no errors
client
package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
new Incomingdata().execute();
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
try
{ System.out.println("Test123");
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
System.out.println("Test1234");
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
System.out.println("Test1235");
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Server
package handy_server.simple_gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//imports for server
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Pandaboy
*/
class ServerGUI extends JFrame implements ActionListener
{
private Socket connection;
private InetAddress ip;
private JTextField t1 = new JTextField(null);
private JTextField t2 = new JTextField(null);
private JTextField t3 = new JTextField(null);
private JButton b2 = new JButton("Send");
private JButton b1 = new JButton("Working");
private JPanel p1 = new JPanel();
private ServerSocket listeningSocket;
private int port= 0;
private ArrayList<Contact> myContacts = new ArrayList<Contact>();
//-------------------------serverGui------------------------------------------------------------
public ServerGUI(int port){
this.port = port;
init();
}
public void init()
{
Container content = getContentPane();
content.setLayout(new FlowLayout());
Font f = new Font("TimesRoman", Font.BOLD, 20);
p1.setLayout(new GridLayout(2, 2));
content.add(p1);
p1.add(t1);
p1.add(b1);
p1.add(t2);
p1.add(t3);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(210, 300);
setVisible(true);
System.out.println("Just about to start the server...");
startServer();
}
public void actionPerformed(ActionEvent e)
{
Object target = e.getSource();
if (target == b1)
{
t1.setText("Button working");
MyHelpers.buildConversations(this, myContacts);
}
if(target == b2)
{
t1.setText("button working2");
String number = t2.getText();
int phone_length = number.length();
if (phone_length <= 20)
{
for(int a=1; a <=(20 - phone_length); a++ )
{
number += " ";
}
}
String msg = t3.getText();
String text = "7"+number+msg;
System.out.print(""+text);
OutputStream o = null;
try
{
o = connection.getOutputStream();
}
catch (IOException ex)
{
Logger.getLogger(ServerGUI.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
}
}
//-----------------------------------------------------------------------------------------------------
//------------------------------startServer------------------------------------------------------------
private void startServer()
{
SwingWorker <Void, String> runningServer = new SwingWorker<Void, String>(){
protected Void doInBackground()
{
System.out.println("in startserver...");
try
{
listeningSocket = new ServerSocket(port);
try
{
ip = InetAddress.getLocalHost();
System.out.println("Please enter this in your phone " + ip.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
while (true)
{
System.out.println("Waiting for connection");
connection = listeningSocket.accept();
InputStream in = connection.getInputStream();
Scanner r = new Scanner(in);
OutputStream o = connection.getOutputStream();
PrintWriter p = new PrintWriter(o);
String message = r.nextLine();
System.out.println("" + message);
t1.setText(message);
// get the message type
// 0 sms 1 contact 2 incoming call
System.out.println(message);
if(message.startsWith("0"))
{
System.out.println(message);
String type = message.substring(1,2);
int theType = Integer.parseInt( type );
String number = message.substring(7, 21).trim();
String theText = message.substring(21);
String theName = MyHelpers.getName(number, myContacts);
System.out.println("Number = "+number);
System.out.println("Sender = "+theName);
System.out.println("Text = "+theText);
Contact cRef = MyHelpers.getContactReference(number, myContacts);
if (cRef != null)
{
cRef.addsms(theType, theName, theText);
}
}
if(message.startsWith("1"))
{
System.out.println(message);
String name = message.substring(1, 31).trim();
String pnumber = message.substring(31, 51).trim();
String email = message.substring(51, 91).trim();
myContacts.add(new Contact(name, pnumber, email));
System.out.println( name + pnumber + email);
}
if(message.startsWith("2"))
{
String unkown = message.substring(0, 1).trim();
String number = message.substring(1, 14).trim();
String theName = MyHelpers.getName(number, myContacts);
System.out.println(""+unkown+""+theName+" Is calling you");
}
if(message.startsWith("5"))
{
System.exit(0);
}
Any Help would be great i am stumped by this
In your server append '\n' to the end of the response so change this
PrintWriter p = new PrintWriter(o);
p.println(text);
p.flush();
System.out.print("text sent"+text);
to this:
PrintWriter p = new PrintWriter(o);
p.println(text + "\n");
p.flush();
System.out.print("text sent"+text);
i think the reason it hangs is because readLine() is looking for '\n' and it never recieves it
while(s.isConnected())
{
String input =r.nextLine();
System.out.println("Client"+input);
}

Categories