Sending Multiple Files Via Socket using ObjectOutputStream - java

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.

Related

Read PDF File from Shared Folder

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

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

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

iTextPdf JTextArea Unicode

I am able to load/save JTextArea unicode (devanagari) contents to file fine. I wanted to print the contents to pdf file so I am using iTextPDF api. My snippet is as below which prints empty file instead of with contents.
package i18n;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import com.itextpdf.awt.PdfGraphics2D;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
public class MyNumbers extends JFrame {
private ResourceBundle rb;
private Font devanagariFont;
public MyNumbers (String language, String fontFile) {
loadResourceBundle(language);
loadFont(fontFile);
display();
}
TextArea txtArea;
private void display() {
String unicode = null;
JPanel labels = new JPanel(new GridLayout(0,2));
JLabel uni = null;
for(int i=0; i<=10; i++) {
unicode = rb.getString("" +i);
labels.add(new JLabel("" + i));
labels.add(uni = new JLabel(unicode));
//uni.setFont(devanagariFont);
}
labels.add(new JLabel("Time"));
labels.add(new ClockLabel());
getContentPane().setLayout(new FlowLayout());
Box b = Box.createVerticalBox();
b.add(labels);
b.add(txtArea = new TextArea(10, 40));
getContentPane().add(b);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
try {
getInputContext().selectInputMethod(new Locale("hi", "IN"));
read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
try {
System.out.println(getInputContext().getLocale());
save();
print();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
});
//setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
String fileName = "MyNumbers.txt";
private void save() throws IOException {
File f = new File(fileName);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
String txt = txtArea.getText();
writer.write(txt);
writer.flush();
writer.close();
}
private void read() throws IOException {
File f = new File(fileName);
if(f.exists() == false) return;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
String line = null;
while((line = reader.readLine()) != null) {
txtArea.append(line + "\n");
}
reader.close();
}
private void loadFont(String fontFile) {
try {
InputStream input = getClass().getResourceAsStream(fontFile);
Font b = Font.createFont(Font.TRUETYPE_FONT, input);
devanagariFont = b.deriveFont(Font.PLAIN, 11);
} catch(Exception e) {
e.printStackTrace();
}
}
private void loadResourceBundle(String language) {
String base = getClass().getName() + "rb";
rb = ResourceBundle.getBundle(base, new Locale(language));
}
static class ClockLabel extends JLabel implements ActionListener {
private ClockLabel() {
new Timer(1000, this).start();
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
public void actionPerformed(ActionEvent e) {
Calendar cal = Calendar.getInstance();
setText(sdf.format(cal.getTime()));
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyNumbers("hi", "Devnew.ttf");
}
});
}
String pdfFileName = "MyNumbers.pdf";
private void print() {
System.out.println("Printing PDF file ..");
try {
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFileName));
document.open();
PdfContentByte cb = writer.getDirectContent( );
PdfGraphics2D g2d = new PdfGraphics2D(cb, PageSize.A4.getWidth(), PageSize.A4.getHeight());
System.out.println(txtArea.getSize());
txtArea.print(g2d);
g2d.dispose();
document.close ();
}
catch(DocumentException de) {
System.err.println(de.getMessage());
}
catch(IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}
Output to console:
hi_IN
Printing PDF file ..
java.awt.Dimension[width=300,height=170]
Please let me know know the fix. I am not setting any font for graphics assuming that the swing JTextArea should be able to handle it. The unicode support is added with indicim.jar Input Method framework. As per output above the Dimension shows that text area is not of zero size.
In order to test above you need 2 files:
indicim.jar and place it in jre/lib/ext
MyNumbers.txt - unicode content file in devanagari as below which as such you can type it yourself in text area and program saves/loads on shutdown/startup. You save it in the project dir of eclipse.
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
अम२ जवान
ऊँ
A pdf file will get created in eclipse project dir but for now its empty.
The problem is that you don't call:
writer.close()
on your PdfWriter. Adding that line at the end of your print() method should do the trick.
EDIT:
Here is an SSCCE (well you still need to add iText lib, version 4.2.0, to your dependencies) that works for me:
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;
public class MyNumbers extends JFrame {
private Font devanagariFont;
public MyNumbers(String language, String fontFile) {
loadResourceBundle(language);
loadFont(fontFile);
display();
}
TextArea txtArea;
private void display() {
String unicode = null;
JPanel labels = new JPanel(new GridLayout(0, 2));
JLabel uni = null;
for (int i = 0; i <= 10; i++) {
unicode = String.valueOf(i);
labels.add(new JLabel("" + i));
labels.add(uni = new JLabel(unicode));
// uni.setFont(devanagariFont);
}
labels.add(new JLabel("Time"));
labels.add(new ClockLabel());
getContentPane().setLayout(new FlowLayout());
Box b = Box.createVerticalBox();
b.add(labels);
b.add(txtArea = new TextArea(10, 40));
getContentPane().add(b);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
try {
getInputContext().selectInputMethod(new Locale("hi", "IN"));
read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
try {
System.out.println(getInputContext().getLocale());
save();
print();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.exit(0);
}
});
// setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
String fileName = "MyNumbers.txt";
private void save() throws IOException {
File f = new File(fileName);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-16"));
String txt = txtArea.getText();
writer.write(txt);
writer.flush();
writer.close();
}
private void read() throws IOException {
File f = new File(fileName);
if (f.exists() == false) {
return;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-16"));
String line = null;
while ((line = reader.readLine()) != null) {
txtArea.append(line + "\n");
}
reader.close();
}
private void loadFont(String fontFile) {
try {
InputStream input = getClass().getResourceAsStream(fontFile);
Font b = Font.createFont(Font.TRUETYPE_FONT, input);
devanagariFont = b.deriveFont(Font.PLAIN, 11);
} catch (Exception e) {
e.printStackTrace();
}
}
private void loadResourceBundle(String language) {
String base = getClass().getName() + "rb";
}
static class ClockLabel extends JLabel implements ActionListener {
private ClockLabel() {
new Timer(1000, this).start();
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
#Override
public void actionPerformed(ActionEvent e) {
Calendar cal = Calendar.getInstance();
setText(sdf.format(cal.getTime()));
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyNumbers("hi", "Devnew.ttf");
}
});
}
String pdfFileName = "MyNumbers.pdf";
private void print() {
System.out.println("Printing PDF file ..");
try {
File pdf = new File(pdfFileName);
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
document.open();
PdfContentByte cb = writer.getDirectContent();
Graphics2D g2d = cb.createGraphics(PageSize.A4.getWidth(), PageSize.A4.getHeight());
System.out.println(txtArea.getSize());
txtArea.printAll(g2d);
g2d.dispose();
document.close();
writer.flush();
writer.close();
Desktop.getDesktop().open(pdf);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
}
}

Categories