I am using this code for read the pdf file from shared folder, but i cannot read the file
package com.example.kuldeep.myapplication;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.playlog.internal.LogEvent;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileFilter;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import static com.example.kuldeep.myapplication.R.id.textView1;
import static com.example.kuldeep.myapplication.R.layout.activity_main14;
import static org.apache.commons.io.comparator.LastModifiedFileComparator.*;
public class Main14Activity extends AppCompatActivity {
private static final String TAG = "Main14Activity";
TextView textView, textiew1;
String CustomerNameRegex = "Customer Name: [a-zA-Z\\s]*",
MobileNumberRegex = "PH:\\s[0-9]*",
JobCardNoRegex = "Jobcard No :\\sJC-[a-zA-Z0-9\\S]*\n[a-zA-Z0-9\\S]*",
ServiceTypeRegex = "Service Type:([a-zA-Z0-9\\s\\S])*GSTIN",
RegistrationNumberRegex = "Reg. No.:\\s[a-zA-Z0-9\\S]*";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main14);
/*listView=(ListView)findViewById(R.id.list);*/
textView = (TextView) findViewById(R.id.text);
textView = (TextView) findViewById(R.id.text1);
jcifs.Config.setProperty("jcifs.netbios.wins", "192.168.1.12");
Thread th = new Thread(new Runnable() {
#Override
public void run() {
SmbFile choice = null;
try {
String yourPeerName = "kuldeep";
String yourPeerPassword = "123";
String yourPeerIP = "192.168.1.12";
final String path = "smb://" + yourPeerIP + "/Scan/";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, yourPeerName, yourPeerPassword);
Log.e("Connected", "Yes");
SmbFile file = new SmbFile(path, auth);
SmbFile[] mFile = file.listFiles();
if (mFile == null || mFile.length == 0) {
return;
}
SmbFile lastmode = mFile[0];
for (int i = 1; i < mFile.length; i++) {
if (lastmode.lastModified() < mFile[i].lastModified()) {
lastmode = mFile[i];
}
}
Log.v(TAG, "File" + lastmode);
String s = String.valueOf(lastmode);
Log.v(TAG, "File" + s);
Log.v(TAG, "File" + lastmode.getInputStream().read());
Log.v(TAG, "File" + lastmode.getName());
final String dat = lastmode.getName().toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(dat);
try {
String parsedText = "";
PdfReader reader = new PdfReader(path + dat);
Log.v(TAG, "File" + reader);
int n = reader.getNumberOfPages();
for (int i = 0; i < n; i++) {
parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, i + 1).trim() + "\n"; //Extracting the content from the different pages
}
Log.v(TAG, "File" + parsedText);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
you declare same textview both
textView=(TextView)findViewById(R.id.text);
textiew1=(TextView)findViewById(R.id.text1);
Related
Iam new into java coding, iam learning and to learn i propose to me create a traceroute program that keep testing the ping response on the route traced.
The first step is get the IP from user and make the traceroute, getting all ip address to be pinged, but iam stuck on this, when i try to add a parsed return of traceroute output to the Jtable, it dont acumullate it, just add the last entry of my while.
Please dont blame my by the bad coding, iam learning.
Iam trying to figure out how to add data to a list and a JTable from a while.
This program get informations from other class, this other class runs a tracert to a ip address and return to Main the tracert results in this format:
13ms;14ms;23ms;192.168.2.3
13ms;14ms;23ms;192.168.2.1
13ms;14ms;23ms;200.122.222.22
this is my table fields: ping1,ping2,ping3,hop
I need to put this data in the table but need to be all ips of the list but iam getting only the last one.
I made alot of tests and commented it because did not workd.
Main.java
package application;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import application.Main.Pinge;
import application.NetworkDiagnostics;
import javafx.application.Application;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
// Layout
FlowPane noRaiz = new FlowPane();
// Cena
Scene minhaCena = new Scene(noRaiz, 400, 500);
// Nós
TextField ip = new TextField();
// Tables
// List lista = new ArrayList<String>();
// lista.add("1;2;3;4");
// List<Pinge> lista = Arrays.asList();
// List<Pinge> lista = Arrays.asList(
// new Pinge("OK","OK","OK","OK")
// );
TableView<Pinge> tabela = new TableView<>();
TableColumn colunahop = new TableColumn<>("Hop");
TableColumn colunaping1 = new TableColumn<>("Ping1");
TableColumn colunaping2 = new TableColumn<>("Ping2");
TableColumn colunaping3 = new TableColumn<>("Ping3");
colunahop.setCellValueFactory(new PropertyValueFactory<>("hop"));
colunaping1.setCellValueFactory(new PropertyValueFactory<>("ping1"));
colunaping2.setCellValueFactory(new PropertyValueFactory<>("ping2"));
colunaping3.setCellValueFactory(new PropertyValueFactory<>("ping3"));
tabela.getColumns().addAll(colunahop, colunaping1, colunaping2, colunaping3);
Button vai = new Button();
vai.setText("vai");
Label texto = new Label();
texto.setText("");
TextArea resultadow = new TextArea();
// Adicionar elementos na cena
noRaiz.getChildren().add(ip);
noRaiz.getChildren().add(vai);
noRaiz.getChildren().add(texto);
noRaiz.getChildren().add(tabela);
// noRaiz.getChildren().add(resultadow);
vai.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#SuppressWarnings("null")
#Override
public void handle(ActionEvent envent) {
String resultado = new String();
ip.setText("registro.br");
vai.setFocusTraversable(true);
texto.setText("Rastreando: " + ip.getText());
resultadow.setText("Rastreando: " + ip.getText());
resultado = application.NetworkDiagnostics.traceRoute(ip.getText());
// tabela.getItems().add(lista);
String[] result = resultado.split("\n");
String payload = null;
// lista.add(resultado);
int x1 = 0;
// lista.add(lista.lastIndexOf(lista)+1, new Pinge("TESTE","TESTE","TESTE","TESTE"));
List<Pinge> lista = null;
while (x1 < result.length) {
System.out.println(x1 + ": " + result[x1]);
String[] result1 = result[x1].split(";");
// payload = payload + result1[3] + ":" + result1[0] + ":" + result1[1] + ":" + result1[2] + "\n";
lista = Arrays.asList(new Pinge(result1[3],result1[0],result1[1],result1[2]));
// lista.add(new Pinge(result1[3],result1[0],result1[1],result1[2]));
resultadow.appendText(result1[3] + ":" + result1[0] + ":" + result1[1] + ":" + result1[2] + "\n");
//resultadow.setText(result[x1]);
x1++;
}
//List<Pinge> lista = Arrays.asList(new Pinge("TESTE","TESTE","TESTE","TESTE"));
tabela.setItems(FXCollections.observableArrayList(lista));
}
});
primaryStage.setScene(minhaCena);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static class Pinge {
private String hop;
private String ping1;
private String ping2;
private String ping3;
public Pinge(String hop, String ping1, String ping2, String ping3) {
this.hop = hop;
this.ping1 = ping1;
this.ping2 = ping2;
this.ping3 = ping3;
}
public String getHop() {
return hop;
}
public void setHop(String hop) {
this.hop = hop;
}
public String getPing1() {
return ping1;
}
public void setPing1(String ping1) {
this.ping1 = ping1;
}
public String getPing2() {
return ping2;
}
public void setPing2(String ping2) {
this.ping2 = ping2;
}
public String getPing3() {
return ping3;
}
public void setPing3(String ping3) {
this.ping3 = ping3;
}
}
public static void main(String[] args) {
launch(args);
}
}
This is the class where do the tracert command
NetworkDiagnostics.java
package application;
import java.io.BufferedWriter;
import application.Main;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NetworkDiagnostics {
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private final String os = System.getProperty("os.name").toLowerCase();
public static String traceRoute(String string) {
String route = "";
String res = "";
int ms = 0;
File arquivo = new File("c:/pedro/tracert.log");
try {
Process traceRt;
traceRt = Runtime.getRuntime().exec("tracert " + string);
// read the output from the command
route = convertStreamToString(traceRt.getInputStream());
route = route.trim().replaceAll(" ", " ").replaceAll(" ", " ").replaceAll(" ms", "ms").replaceAll(" ", ",");
String[] split = route.trim().split("\n");
//regex ip and domain
String IPADDRESS_PATTERN = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
String DOMAIN_PATTERN = "^(www\\.|)(([a-zA-Z0-9])+\\.){1,4}[a-z]+$";
Pattern patternIP = Pattern.compile(IPADDRESS_PATTERN);
// Pattern patternDo = Pattern.compile(DOMAIN_PATTERN);
int x = 1;
while (x < split.length) {
// debug
System.out.println(split[x]);
int y = 0;
String[] details = split[x].split(",");
while (y < details.length) {
Matcher matcherIP = patternIP.matcher(details[y]);
// Matcher matcherDO = patternDo.matcher(details[y]);
if (details[y].contains("ms"))
{
res = res + details[y] + ";";
}
if (matcherIP.find()) {
res = res + matcherIP.group() + "\n";
}
y++;
}
x++;
}
convertStreamToString(traceRt.getErrorStream());
} catch (IOException e) {
}
try {
if (!arquivo.exists()) {
// cria um arquivo (vazio)
arquivo.createNewFile();
}
// caso seja um diretório, é possível listar seus arquivos e diretórios
File[] arquivos = arquivo.listFiles();
// escreve no arquivo
FileWriter fw = new FileWriter(arquivo, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(route.replaceAll("\\s", " "));
bw.newLine();
bw.close();
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return res;
}
}
I am getting an cannot resolve method error when i do this:
DataOutputStream os = newDataOutputStream(client.getOutputStream());
My imports:
import android.os.Bundle;
import android.app.Activity;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Code for class
#SuppressWarnings("deprecation")
class sentMessage implements Runnable {
public void run() {
try {
Socket client = serverSocket.accept();
DataOutputStream os = newDataOutputStream(client.getOutputStream());
str = smessage.getText().toString();
msg = msg + "\n Server : " + str;
handler.post(new Runnable() {
public void run() {
chat.setText(msg);
}
});
os.writeBytes(str);
os.flush();
os.close();
client.close();
} catch (IOException e) {
}
}
}
You're missing a space.
DataOutputStream os = new DataOutputStream(client.getOutputStream());
^
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();
}
}
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.
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);
}