I am trying to read GPS data from a serial port(ttyACM0) in java using jssc jar which I need to display as a label in a JavaFx application. I have a created a thread for reading the GPS data but this thread is consuming 100% CPU(checked using top command + Shift H) because of which my GUI is getting freezed. This is a sample code I have written for reading GPS data
Serial Interface
import jssc.*;
public class SerInterface {
String portName;
int baud;
boolean lineMode;
// The chosen Port itself
SerialPort port;
public byte[] recvBuff;
public SerInterface(String portName, int baud, boolean lineMode) {
this.portName = portName;
this.baud = baud;
this.lineMode = lineMode;
recvBuff = new byte[8192];
openPort();
if((port == null) || (!port.isOpened()))
System.out.println(portName + " not opened successfully");
}
void openPort() {
port = new SerialPort(portName);
if(port == null)
return;
try {
port.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
try {
if(port.isOpened())
port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
else
return;
} catch (SerialPortException e) {
e.printStackTrace();
}
System.out.println(portName + " opened successfully");
}
public int recvData() {
int len = 0;
if(port.isOpened()) {
try {
byte[] buff = port.readBytes();
if((buff == null) || (buff.length == 0))
return 0;
len = buff.length;
if(len > recvBuff.length)
len = recvBuff.length;
System.arraycopy(buff, 0, recvBuff, 0, len);
buff = null;
} catch (SerialPortException e) {
e.printStackTrace();
}
}
return len;
}
public void sendData(byte[] sendBuff, int len) {
if(port.isOpened()) {
try {
port.writeBytes(sendBuff);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public boolean validatePort() {
if(!port.isOpened()) {
openPort();
if(port.isOpened())
return true;
else
return false;
}
else
return true;
}
public void flushPort() {
if(port.isOpened()) {
try {
port.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
public void closePort() {
if(port.isOpened()) {
try {
port.closePort();
System.out.println("port closed");
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
}
GPSReceiver thread extends SerInterface and implements Runnable
#Override
public void run() {
flushPort();
while(true) {
if(!validatePort()) {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
int dataLength = recvData();
if(dataLength < 2)
continue;
try {
InputStream gpsStream = new ByteArrayInputStream(recvBuff, 0, dataLength);
BufferedReader br = new BufferedReader(new InputStreamReader(gpsStream, StandardCharsets.US_ASCII));
while(true) {
try {
if (!((output = br.readLine()) != null)) break;
} catch (IOException e) {
e.printStackTrace();
}
extractData();
}
}
catch(NullPointerException e) {
e.printStackTrace();
}
}
Main Thread
GPSInterface objGPSThreadInterface = new GPSInterface(GPSPortName, 9600, true);
GPSThreadInt = new Thread(objGPSThreadInterface, "GPSINT");
I am using jdk-13.0.1 and jssc-2.9.1 jar
I have written a multi-client TCP server that has the dual purpose of sending Json (text based) command strings and also sending an SQLite database file to multiple clients. Everything is working nicely except... the database file uses the special character hex81 (decimal 129) for some internal purpose. When I read the database file into a byte array, Java converts this character to decimal -127 because of Java's signed representation of bytes. However the socket is actually transmitting this character as hex3F. So when I receive the save the data in the client and save it to a file, the database is corrupt due to the presence of h3F chars instead of h81.
Why is this happening and how do I correct it?
Here is the complete code that I am using for the server (a new instance of this class is started by a separate TCPServer class whenever a client connects):
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static ByteArrayOutputStream txBuffer2 = new ByteArrayOutputStream();
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private DataOutputStream out2 = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new DataOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (txBuffer2.size() != 0) {
byte[] result = txBuffer2.toByteArray();
System.out.println(result[745] + "," + result[746] + "," + result[747] + "," + result[748] + "," + result[749] + "," + result[750]);
out2.write(result);
out2.flush();
txBuffer2.reset();
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
synchronized (txBuffer2) {
file = new File(filename);
byte[] content = new byte[(int)file.length()];
FileInputStream fin;
try {
fin = new FileInputStream(file);
fin.read(content);
System.out.println(content[745] + "," + content[746] + "," +content[747] + "," +content[748] + "," + content[749] + "," + content[750]);
txBuffer2.write(content);
fin.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
f.printStackTrace();
}
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
So as EJP suggested, the problem is due to using readers and writers.
The following code now works as expected (thanks for the tip EJP). I will get around to addressing the issue raised by VGR about wrapping client.getOutputStream() in both a PrintWriter and a BufferedOutputStream, but for now the code works nicely (this is a work in progress).
public class TCPServerThread extends Thread {
// Connect status constants
private final static int NULL = 0;
private final static int DISCONNECTED = 1;
private final static int DISCONNECTING = 2;
private final static int BEGIN_CONNECT = 3;
private final static int CONNECTED = 4;
private final static String END_SESSION = new Character((char)0).toString(); // Indicates the end of a session
// Connection state info
private int connectionStatus = DISCONNECTED;
private static StringBuffer txBuffer = new StringBuffer("");
private static BufferedOutputStream out2 = null;
private static File file;
// TCP Components
private ServerSocket serverSocket = null;
private Socket clientSocket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private static BufferedInputStream fileData = null;
private String s = "";
private DecodeJson dj = new DecodeJson();
private boolean doRun;
public TCPServerThread(Socket socket) throws IOException {
doRun = true;
clientSocket = socket;
changeStatusTS(BEGIN_CONNECT, true);
}
public void run() {
while (doRun) {
try { // run every ~10 ms
Thread.sleep(10);
}
catch (InterruptedException e) {}
if (Mainscreen.shutdown == true || TCPClient.close == true)
connectionStatus = DISCONNECTING;
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
out2 = new BufferedOutputStream(clientSocket.getOutputStream());
TCPServer.writers.add(out); // add this socket to the connected clients list
changeStatusTS(CONNECTED, true);
}
// If error, clean up and output an error message
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Send data
if (txBuffer.length() != 0) {
for (PrintWriter writer : TCPServer.writers) {
writer.print(txBuffer);
writer.flush();
if(writer.checkError()) {
closeSocket();
changeStatusTS(DISCONNECTING, true);
}else {
changeStatusTS(NULL, true);
}
}
txBuffer.setLength(0);
}
if (fileData != null) {
byte[] buffer = new byte[(int) file.length()];
for (int read = fileData.read(buffer); read >=0; read = fileData.read(buffer)) out2.write(buffer, 0, read);
out2.flush();
fileData = null;
}
// Receive data
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
// Check if it is the end of a transmission
if (s.equals(END_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Otherwise, receive text
else {
dj.receiveString(s);
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
System.out.println("Socket error " + e);
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
// Tell clients to disconnect as well
if (out != null) {
out.print(END_SESSION);
out.flush();
}
// Clean up (close all streams/sockets)
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break;
}
}
}
// Add command to text send-buffer
public static void sendString(String s) {
synchronized (txBuffer) {
txBuffer.append(s + "\n");
}
}
// Add file data to binary send buffer
public static void sendFile(String filename) {
file = new File(filename);
try {
fileData = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void changeStatusTS(int newConnectStatus, boolean noError) {
// Change state if valid state
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
}
private void closeSocket(){
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
}
// Cleanup for disconnect
private void cleanUp() {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
}
catch (IOException e) { serverSocket = null; }
try {
if (clientSocket != null) {
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e) { clientSocket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) { in = null; }
if (out != null) {
TCPServer.writers.remove(out); // remove this socket for the connected sockets list
out.close();
out = null;
}
doRun = false;
}
}
I have manage to write a async class that send a picture over broadcast and wait for clients inverse ack and then send the packages that were not received...
The issue I am facing is that for sending 1mb picture it takes really long (1min aprox) to complete ussing only two phones connecting to each other via wifi. Here is my code (sorry for the long code)
SENDER CLASS
public class SenderBroadcastAsyncTask extends AsyncTask<File, Integer, String> {
Context context;
public SenderBroadcastAsyncTask(Context context) {
this.context = context.getApplicationContext();
}
#Override
protected String doInBackground(File... imagen) {
Log.d("SENDER","INICIANDO EL SOCKET PARA ENVIAR");
InetAddress group = null;
try {
group = InetAddress.getByName("192.168.49.255");
} catch (UnknownHostException e) {
e.printStackTrace();
}
int port =1212;
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
DatagramSocket rsocket = null;
try {
rsocket = new DatagramSocket(1513);
} catch (SocketException e) {
e.printStackTrace();
}
try {
rsocket.setSoTimeout(2000);
} catch (SocketException e) {
e.printStackTrace();
}
for (File i:imagen) {
Bitmap bitmap = BitmapFactory.decodeFile(i.getAbsolutePath());
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream2);
byte[] prebuf = stream2.toByteArray();
mandar(prebuf, rsocket, socket, group, port);
}
return "ok";
}
public void mandar(byte[] prebuf,DatagramSocket rsocket,DatagramSocket socket,InetAddress group,int port) {
int DATAGRAM_MAX_SIZE = 50*1024;
int cantidadpedazos = (int) Math.ceil(prebuf.length / (float) DATAGRAM_MAX_SIZE);
Log.d("Pedazos", Integer.toString(cantidadpedazos));
//Loop peaces
for (int i = 1; i <= cantidadpedazos; i++) {
enviar(i,socket,group,port,prebuf,DATAGRAM_MAX_SIZE,cantidadpedazos);
}
////FINAL DONE
String message_to_send = "DONE";
byte[] ultimo = message_to_send.getBytes();
DatagramPacket ultimopaquete = new DatagramPacket(ultimo, ultimo.length, group, port);
try {
socket.send(ultimopaquete);
} catch (IOException e) {
e.printStackTrace();
}
/*AFTER DONE WAIT FOR INVERSE ACK OF NUMERED PACKETS*/
boolean mandarfaltan = false;
boolean ack = false;
int countertoend=0;
boolean cancelcheck = false;
while (!ack) {
byte[] recibir = new byte[5];
DatagramPacket pkgrecibir = new DatagramPacket(recibir, 0, recibir.length);
Log.d("UDP", "S: Receiving...");
try {
rsocket.receive(pkgrecibir);
} catch (SocketTimeoutException e) {
Log.d("timeout","TIMEOUT EXCEPTION");
if (mandarfaltan) {
try {
socket.send(ultimopaquete);
} catch (IOException q) {
q.printStackTrace();
}
if (countertoend ==7)
{
Log.d("error","timeout error no response to done");
socket.close();
rsocket.close();
break;
}
cancelcheck = true;
countertoend++;
} else {
Log.d("ACK", "TIMEOUT CANELING PASSING TO DONE");
socket.close();
rsocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
mandarfaltan = true;
if (!cancelcheck) {
String faltast = new String(pkgrecibir.getData()).trim();
Integer faltaint = Integer.parseInt(faltast); ////euivalent to for i
enviar(faltaint, socket, group, port, prebuf, DATAGRAM_MAX_SIZE, cantidadpedazos);
if (new String(pkgrecibir.getData()).trim().contains("DONE")) {
Log.d("ACK", "Received" + " " + new String(pkgrecibir.getData()).trim());
ack = true;
}
}
cancelcheck = false;
}
}
public void enviar(int i,DatagramSocket socket,InetAddress group,int port,byte[] prebuf,int DATAGRAM_MAX_SIZE,int cantidadpedazos){
//for (int i = 1; i <= cantidadpedazos; i++) {
////EN cada interaccion del for clono el array con las ip q recibiran el paquete
//ArrayList<String> finallist = (ArrayList<String>) tosend.clone();
String final_str = null;
String counter_str = Integer.toString(i);
int len = counter_str.length();
byte[] final_strbyte = new byte[5];
Log.d("HEADER", counter_str + " TAMANO " + Integer.toString(len));
switch (len) {
case 1:
final_str = "0000" + Integer.toString(i);
final_strbyte = final_str.getBytes();
break;
case 2:
final_str = "000" + counter_str;
final_strbyte = final_str.getBytes();
break;
case 3:
final_str = "00" + counter_str;
final_strbyte = final_str.getBytes();
break;
case 4:
final_str = "0" + counter_str;
final_strbyte = final_str.getBytes();
break;
case 5:
final_str = counter_str;
final_strbyte = final_str.getBytes();
break;
}
byte[] slice, imagetosend;
DatagramPacket packet;
if (i == 1) {
slice = Arrays.copyOfRange(prebuf, 0, i * DATAGRAM_MAX_SIZE);
imagetosend = new byte[slice.length + 5];
for (int s = 0; s < 5; s++) {
imagetosend[s] = final_strbyte[s];
}
for (int s = 0; s < slice.length; s++) {
imagetosend[s + 5] = slice[s];
}
packet = new DatagramPacket(imagetosend, imagetosend.length, group, port);
for (int s = 0; s < 1; s++) {
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (i == cantidadpedazos) {
slice = Arrays.copyOfRange(prebuf, (i - 1) * DATAGRAM_MAX_SIZE, prebuf.length);
imagetosend = new byte[slice.length + 5];
for (int s = 0; s < 5; s++) {
imagetosend[s] = final_strbyte[s];
}
for (int s = 0; s < slice.length; s++) {
imagetosend[s + 5] = slice[s];
}
packet = new DatagramPacket(imagetosend, imagetosend.length, group, port);
for (int s = 0; s < 2; s++) {
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
slice = Arrays.copyOfRange(prebuf, ((i - 1) * DATAGRAM_MAX_SIZE), i * DATAGRAM_MAX_SIZE);
imagetosend = new byte[slice.length + 5];
for (int s = 0; s < 5; s++) {
imagetosend[s] = final_strbyte[s];
}
for (int s = 0; s < slice.length; s++) {
imagetosend[s + 5] = slice[s];
}
packet = new DatagramPacket(imagetosend, imagetosend.length, group, port);
for (int s = 0; s < 2; s++) {
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
RECEIVE CLASS
public class ReceiverBroadcastAsyncTask extends AsyncTask<Void, Integer ,String > {
boolean running = true;
Context context;
//public int counter = 1;
public ReceiverBroadcastAsyncTask(Context context) {
this.context = context.getApplicationContext();
}
#Override
protected String doInBackground(Void... params) {
Log.d("CLASS","INSIDE_MULTICAST RECEIVER");
////receive socket
int port =1212;
DatagramSocket socket = null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
try {
socket.setBroadcast(true);
} catch (SocketException e) {
e.printStackTrace();
}
//////send socket
int eport = 1513;
InetAddress eip = null;
try {
eip = InetAddress.getByName("192.168.49.1");
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramSocket esocket = null;
try {
esocket = new DatagramSocket(eport);
} catch (SocketException e) {
e.printStackTrace();
}
//////end sockets
/////Array used for organize the received packages and log the received headers to send inverse ack
ArrayList<Integer> headers = new ArrayList<Integer>();
ArrayList<byte[]> contenido = new ArrayList<byte[]>();
for (int a=0;a<30000;a++)
{
contenido.add(null);
}
ByteArrayOutputStream imagen = new ByteArrayOutputStream();
int counter = 0;
////////end arrays
//////Start receive
while(true)
{
byte[] message = new byte[60*1024];
DatagramPacket recv_packet = new DatagramPacket(message, message.length);
try {
socket.receive(recv_packet);
} catch (IOException e) {
e.printStackTrace();
}
byte[] order = new byte[5];
Log.d("UDP", "S: Receiving...escuchando en el puerto " + recv_packet.getPort() );
String rec_str;
String rec_order;
Log.d("PACKAGE LENGTH",Integer.toString(recv_packet.getLength()));
if(recv_packet.getLength()>5) ////Packages that are minor to 5 are done packages
{
byte[] buff = new byte[recv_packet.getLength()-5];
System.arraycopy(recv_packet.getData(), 5, buff, 0, buff.length);
System.arraycopy(recv_packet.getData(), 0, order, 0, 5);
rec_str = new String(buff);
rec_order = new String(order);
Log.d("DATA", " " + counter + " " + rec_order);
/////add int counter to array
///////process buff to add to contenido array whit headers as index
if (process(headers,contenido,rec_str,imagen,buff,counter,Integer.parseInt(rec_order),esocket)){
counter =Integer.parseInt(rec_order);}
////end buff processing
}
else ////done package
{
byte[] buff = new byte[recv_packet.getLength()];
System.arraycopy(recv_packet.getData(), 0, buff, 0, buff.length);
rec_str = new String(buff);
counter=0;
///procesar paquetes done o querys..
if (process(headers,contenido,rec_str, imagen, buff, counter, 0,esocket)){
//counter++;
}
}
////end while
}
////end doInBackground
}
/*image processing bound to notification*/
public void procesar( ByteArrayOutputStream imagen) {
Log.d("IMAGEN_PROCESSING", "INSIDE....");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(fullPath, "something" + timeStamp + ".png");
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
file.createNewFile();
fOut = new FileOutputStream(file.getPath());
Log.d("File created", file.getAbsolutePath());
fOut.write(imagen.toByteArray());
if(fOut!=null){fOut.close();}
} catch (Exception e) {
}
Bitmap bmp = BitmapFactory.decodeByteArray(imagen.toByteArray(),0,imagen.toByteArray().length);
notification(context,bmp,file);
}
/*end image processing */
/*INVERSE ACK*/
public void inverseack(ArrayList<byte[]> contenido ,ArrayList<Integer> headers,DatagramSocket esocket){
running = false;
Set<Integer> noduplicate = new HashSet<>();
noduplicate.addAll(headers);
headers.clear();
headers.addAll(noduplicate);
Collections.sort(headers);
ArrayList<Integer> faltante= new ArrayList<Integer>();
if (headers.size()!=0)
{
for (int o=1 ; o<=headers.get(headers.size()-1);o++)
{
if(!headers.contains(o)) {
faltante.add(o);
Log.d("Falta"," "+o);
}
}
if (faltante.isEmpty()) {
Log.d("PROCESAR","YA ESTA TODO, listo para procesar imagen");
ByteArrayOutputStream finalbyte = new ByteArrayOutputStream();
for(byte[] w:contenido)
{
if (w!=null) {
finalbyte.write(w, 0, w.length);
}
else break;
}
String message_to_send = "DONE";
byte[] ultimo = message_to_send.getBytes();
InetAddress group = null;
try {
group = InetAddress.getByName("192.168.49.1");
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramPacket ultimopaquete = new DatagramPacket(ultimo, ultimo.length, group, 1513);
try {
esocket.send(ultimopaquete);
} catch (IOException e) {
e.printStackTrace();
}
procesar(finalbyte);
headers.clear();
contenido.clear();
/////imagen processing ready ... process
Log.d("PROCESAR","YA ESTA TODO, listo para procesar imagen");
}
else {
for (int enviar : faltante) {
String faltantevalue = Integer.toString(enviar);
byte[] enviarfaltante = new byte[faltantevalue.length()];
enviarfaltante = faltantevalue.getBytes();
InetAddress group = null;
try {
group = InetAddress.getByName("192.168.49.1"); //<-- Wifi direct group server ip address
} catch (UnknownHostException e) {
e.printStackTrace();
}
DatagramPacket ultimopaquete = new DatagramPacket(enviarfaltante, enviarfaltante.length, group, 1513);
try {
esocket.send(ultimopaquete);
} catch (IOException e) {
e.printStackTrace();
}
}
}
faltante.clear();
running=true;
///end for
}///end else
////end inverseack
}
///////Process received packages
public boolean process(ArrayList<Integer> headers,ArrayList<byte[]> contenido,String string,ByteArrayOutputStream total,byte[] buff,int counter,int rec,DatagramSocket esocket)
{
Log.d("rec" + Integer.toString(rec),"counter " + Integer.toString(counter));
if (string.contains("DONE")) {
Log.d("INVERSEACK","SENDING INVERSE ACK");
if (running){ inverseack(contenido,headers,esocket);}
counter = 0;
//return false;
}
else if (rec != counter) {
contenido.set(rec-1,buff);
headers.add(rec);
Log.d("RECIBED", "NEW PACKAGE WILL BE SEND");
return true;
}
else{return false;}
return false;
}
///////////////NOTIFICATION
public void notification(Context context,Bitmap bpm, File imagen) {
Intent pendingintent = new Intent();
pendingintent.setAction(Intent.ACTION_VIEW);
pendingintent.setDataAndType(Uri.fromFile(imagen),"image/*");
PendingIntent intentpending = PendingIntent.getActivity(this.context, 0, pendingintent, 0);
NotificationManager notification = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noti = new Notification.Builder(context)
.setContentTitle("Photo!")
.setContentText("Photo CLICK to see")
.setSmallIcon(R.drawable.photo)
.setContentIntent(intentpending)
.setLargeIcon(bpm)
.setLights(-256, 100, 100)
.build();
notification.notify(0,noti);
}
#Override
protected void onPostExecute(String result) {
//do whatever...
}
protected void onProgressUpdate(Integer... Progress)
{
}
}
I really appreciate if someone can check and let me know what may be causing that BIG delay on file reception. (it is udp it´s suppose to be quick)
Thanks in advance
For the chat program in android side I am sending message via DataInput stream as
Socket sck = new Socket();
sck.connect(new InetAddress("192.168.1.91",1500),2000);
if(sck.isConnected())
{
DataOutputStream os = new DataOutputStream(sck.getOutputStream());
os.writeUTf(msg);
System.out.println("Message sent");
}
and on the Server side My code is
ServerSocket serv = new ServerSocket(1500);
Socket sock = serv.accept();
DataInputStream is = new DataInputStream(sock.getInputStream);
String ans = is.readUTF();
System.out.println("Got"+ans);
But on server side it seems it does not received anything and still waiting for the message. But on client side It shows message sent.
Here is my full code.
package in.prasilabs.eagleeye;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class EagleClient extends Thread
{
public int ret = 0;
private String ip;
private int port;
private Socket sck;
private boolean estb = false;
private DataInputStream is;
private DataOutputStream os;
private String rmsg = null;
private String msg;
private String username;
private String password;
public String reply;
Data dt = new Data();
public EagleClient()
{
}
public EagleClient(String ip, int port, String username, String password)
{
this.ip = ip;
this.port = port;
this.username = username;
this.password = password;
}
public void run()
{
establish();
if(estb == true)
{
sendInfo(username,password);
}
}
public void establish()
{
int time_out = 2000;
try
{
System.out.println("trying to connect");
sck = new Socket();
sck.connect(new InetSocketAddress(dt.getIp(),dt.getServerPort()),time_out);
estb = true;
System.out.println("Established");
}
catch (UnknownHostException e)
{
ret =0;
e.printStackTrace();
}
catch (IOException e)
{
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
if(estb == true)
{
try {
is = new DataInputStream(sck.getInputStream());
os = new DataOutputStream(sck.getOutputStream());
dt.setOS(os);
dt.setIS(is);
System.out.println("Messages are ready to send");
} catch (IOException e)
{
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void sendInfo(String user,String password)
{
Data dt = new Data();
is = dt.getIS();
os = dt.getOS();
String drport = Integer.toString(dt.getdrPort());
try {
os.writeUTF("logn");
System.out.println("Sending user info");
os.writeUTF(dt.getUsername());
os.writeUTF(dt.getPassword());
os.writeUTF(drport);
reply = is.readUTF();
if(reply.equals("success"))
dt.setLoginStatus(true);
else
dt.setLoginStatus(false);
System.out.println("ACk recieved");
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int sendMessage(String msg)
{
Data dt = new Data();
os = dt.getOS();
is = dt.getIS();
this.msg = msg;
try {
os.writeUTF(msg);
System.out.println("Client :" +msg);
recieveMessage();
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void recieveMessage()
{
try {
System.out.println("Trying to get acknowledgement");
sck.setSoTimeout(2000);
rmsg = is.readUTF();
if(rmsg.equals(msg))
{
System.out.println("Ack recvd" +rmsg);
ret = 1;
}
else if(!msg.equalsIgnoreCase(rmsg))
{
//sendMessage();
Thread.sleep(100);
System.out.println("Retrying");
rmsg = is.readUTF();
System.out.println("Ack recvd" +rmsg);
ret = 1;
}
else
{
System.out.println("Message not recieved");
ret = 0;
}
} catch (IOException e) {
ret = 0;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
Try to use something like this:
String message = "";
while (!"end".equals(message)) {
if (is.available() != 0) {
message = dis.readUTF();
System.out.println(message);
}
}
I checked this - working. Server must be up before client will send message.
i have written a java code to transfer files from one server to another using the concept of socket programming. now in the same code i also want to check for the network connection availability before each file is transferred. i also want that the files transferred should be transferred according to their numerical sequence. And while the files are being transferred the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.
i will really appreciate if someone can help me with the code. i am posting the code i have written for file transfer.
ClientMain.java
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("E:/temp/movies/");
main.setDstPath("D:/tcp/movies");
main.createConnection();
}
}
(DirectoryTxr.java)
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
(ServerMain.java)
public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
(DirectoryRcr.java)
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.
run the ClientMain.java and ServerMain.java
You can sort an array using Arrays.sort(...)
ie
String[] childFiles = file.list();
Arrays.sort(childFiles);
As I understand it, this will sort the files in natural order, based on the file name.
You can modify this by passing a custom Comparator...
Arrays.sort(childFiles, new Comparator<File>() {...}); // Fill out with your requirements...
Progress monitoring will come down to your requirements. Do you want to see only the overall progress of the number of files, the individual files, a combination of both?
What I've done in the past is pre-iterated the file list, calculated the total number of bytes to be copied and used a ProgressMonitor to display the overall bytes been copied...
Otherwise you will need to supply your own dialog. In either case, you will need use SwingUtilities.invokeLater to update them correctly.
Check out Concurrency in Swing for more details.
Network connectivity is subjective. You could simply send a special "message" to there server and wait for a response, but this only suggests that the message was sent and a recipt was received. It could just as easily fail when you start transfering the file again...