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();
}
}
Related
I'm trying to have my program print a few "funny" images whenever it detects motion. Everything works by itself but when I put the if(detection == true) statement into the program, the variable doesn't update. How could I get it to update inside of the motionDetected function?
I've tried using boolean and int for the variable but I think it could be with the way I've structured it.
package printstuff;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.function.Function;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamMotionDetector;
import com.github.sarxos.webcam.WebcamMotionEvent;
import com.github.sarxos.webcam.WebcamMotionListener;
/**
* Detect motion.
*
* #author Bartosz Firyn (SarXos)
*/
public class DetectMotion implements WebcamMotionListener {
public static boolean detection = false;
public DetectMotion() {
//creates a webcam motion detector
WebcamMotionDetector detector = new WebcamMotionDetector(Webcam.getDefault());
detector.setInterval(100); // one check per 100 ms
detector.addMotionListener(this);
detector.start();
}
#Override
public void motionDetected(WebcamMotionEvent wme) {
//detects motion and should change the detection variable
System.out.println("Detected motion");
detection = true;
}
public static void main(String[] args) throws IOException, Exception {
new DetectMotion();
System.in.read(); // keep program open
final String[] catImages = new String[4];
//all the images
catImages[0] = "https://i.ytimg.com/vi/3v79CLLhoyE/maxresdefault.jpg";
catImages[1] = "https://i.imgur.com/RFS6RUv.jpg";
catImages[2] = "https://kiwifarms.net/attachments/dozgry5w4ae3cut-jpg.618924/";
catImages[3] = "https://www.foodiecrush.com/wp-content/uploads/2017/10/Instant-Pot-Macaroni-and-Cheese-foodiecrush.com-019.jpg";
//statement does not work..
if(detection == true)
{
for(int i=0; i<4; i++)
{
//saves the picture inside of the array to image.jpg
String imageUrl = catImages[i];
String destinationFile = "image.jpg";
saveImage(imageUrl, destinationFile);
//sends print job to printer
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0)
throw new RuntimeException("No printer services available.");
PrintService ps = pss[0];
System.out.println("Printing to " + ps);
DocPrintJob job = ps.createPrintJob();
FileInputStream fin = new FileInputStream("image.jpg");
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
job.print(doc, pras);
fin.close();
java.util.concurrent.TimeUnit.SECONDS.sleep(15);
}
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
//converts url into image
URL url = new URL(imageUrl);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}
Im trying to build an Installer/Updater for a project im working on.
My only problem im facing is that my variable of my progess bar doesn't want to be displayed in a label :C.
I already looked up and found an answer from Sebastian who said
myLabel.textProperty().bind(valueProperty); should work but ... well you guess the outcome.
Eclipse says I have to change the type of my int to: ObservableValue<? extends String> and when I changed it it says I have to change it back to int. I dont know what I have to do now ://
EDIT: Full code of my controller class
package application;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
public class Controller {
#FXML
ProgressBar pb;
Label progText;
public void install(){
new Thread(new Runnable() {
#Override public void run() {
download();
}}).start();
};
public void load(){
new Thread(new Runnable() {
#Override public void run() {
download();
Unzip.extract();
System.out.println("Finished");
}}).start();
};
public void download(){
try {
System.out.println("Start");
URL url = new URL("https://www.dropbox.com/s/27d4us64oqifuph/modpack.zip?dl=1");
HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(
"modpack.zip");
java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024);
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in.read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
//calculate progress
int cp = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 10000);
DoubleProperty progress = new SimpleDoubleProperty(0);
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001);
progText.textProperty().bind(progress.asString());
bout.write(data, 0, x);
}
bout.close();
in.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
}
Create a DoubleProperty that is bound to the label and is updated when you update the progressbar.
DoubleProperty progress = new SimpleDoubleProperty(0);
progText.textProperty().bind(progress.asString());
...
// update progress bar
pb.setProgress(cp*0.0001);
progress.setValue(cp*0.0001)
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.
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);
}
I am trying to read a log file continuously where the logs are being written ,both the processes are happening simultaneously.I am using rolling file appender for generating logs but the problem is ,when the file is about to change sometimes the data written when the file is nearing end is not read.Here is my code that generates log file continuously.
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Slf4jSample {
static Logger logger = LoggerFactory.getLogger(Slf4jSample.class);
public static void main(final String[] args) {
int delay = 0; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
int i = 0;
public void run() {
// Task here ...
for (i = 0; i < 50; i++) {
logger.error("testing" + i);
System.out.println(i);
}
}
}, delay, period);
}
}
and here is my code that is reading it continuously.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.mobility.config.ParseConfig;
import com.mobility.mail.SendMail;
import com.mobility.vo.ConfigurationVO;
import com.mobility.vo.LogVO;
import javax.mail.*;
TimerTask fileWatcherTask = new LogWatcher(fileName) {
long addFileLen = fileName.length();
FileChannel channel, oldChannel;
FileLock lock, oldLock;
#Override
protected void onChange(File file) {
RandomAccessFile access = null;
RandomAccessFile oldAccess = null;
int level = 0;
try {
access = new RandomAccessFile(file, "rw");
oldAccess = new RandomAccessFile(prevFileName, "rw");
channel = access.getChannel();
lock = channel.lock();
oldChannel = oldAccess.getChannel();
oldLock = oldChannel.lock();
// System.out.println("addFileLen>>" + addFileLen);
if (file.length() <= addFileLen) {
System.out.println("in if>>");
// reading old file
if (prevFileName.exists()) {
parsingLog(oldAccess, addFileLen,level);
addFileLen = file.length();
}
// reading old file ends
// Seek to 0th position when the file changes.
parsingLog(access, 0,level);
} else {
// access.seek(addFileLen);
parsingLog(access, addFileLen,level);
System.out.println("else>>>");
addFileLen = file.length();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
lock.release();
oldLock.release();
} catch (IOException e1) {
e1.printStackTrace();
} // Close the file
try {
channel.close();
oldChannel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer();
// repeat the check every second
long scheduleTimer = Long.parseLong(properties
.getProperty("scheduler.timer"));
timer.schedule(fileWatcherTask, new Date(), scheduleTimer);
}
}
public void parsingLog(RandomAccessFile access, long fileLength, int level) {
List<String> logList = new ArrayList<String>();
int flag = 0;
String line = null;
try {
access.seek(fileLength);
while ((line = access.readLine()) != null) {
System.out.println("after reading line >"+line);
}
}catch(Exception e){
}
}
PS:it doesn't read the contents when it is nearing end.
I would open the file until it has been fully read and only close it when you have finished reading it. This may require your logger to create a new file each time, but you are unlikely to miss anything this way.