How to solve java.lang.ClassNotFoundException in eclipse - java

I tried to create exe file from my code but it's get me error
java.lang.ClassNotFoundException: Access2
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
I used exe4j tool to generate exe from jar file
I used Jdk 1.8.0_25
and this a part of my main class (Access2)
public class Access2
{
BufferedReader in;
Writer out;
String CommData = "";
String TextData = "";
int FrameNo = 1;
String STX = String.valueOf('\002');
String ETX = String.valueOf('\003');
String EOT = String.valueOf('\004');
String ENQ = String.valueOf('\005');
String ACK = String.valueOf('\006');
String LF = String.valueOf('\n');
String CR = String.valueOf('\r');
String DEL = String.valueOf('\007');
String NAK = String.valueOf('\025');
String SYN = String.valueOf('\026');
String ETB = String.valueOf('\027');
String CRLF = this.CR + this.LF;
String enc;
String LastType = "";
String PatientID;
String PatientName;
String SampleID;
String Result = "";
String Parameter = "";
String PatientComment;
String SampleComment;
String ResultComment = "";
String QuerySampleID;
boolean QueryAsked = false;
Connection connection = null;
Statement stmt = null;
PreparedStatement prepStatement = null;
ResultSet rs = null;
String machine = Setting.GetPropVal("MachineName");
ArrayList<String> DataToSend = new ArrayList();
int Max_Farme_Size = 240;
int FIndex = 1;
int CurIndex = 0;
int RowIndex = 1;
String Frame_Sep;
int retries = 6;
Connection connection2 = null;
Statement stmt2 = null;
PreparedStatement prepStatement2 = null;
ResultSet rs2 = null;
public Access2(Socket s)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(s.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public Access2(SerialPort ser)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(ser.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(ser.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void NextFrameNo()
{
this.FrameNo += 1;
if (this.FrameNo > 7) {
this.FrameNo = 0;
}
}
public void SaveData(String data)
{
String data2save = data.replaceAll(this.ENQ, "<ENQ>").replaceAll(this.STX, "<STX>").replaceAll(this.ETX, "<ETX>").replaceAll(this.EOT, "<EOT>").replaceAll(this.CR, "<CR>").replaceAll(this.CRLF, "<CRLF>").replaceAll(this.ETB, "<ETB>");
LogFile.createLog(this.machine + "_" + CurrentDate.getDate(2) + ".txt", "\r\n[" + CurrentDate.getDate(1) + "]" + ":" + data2save);
}
public String[] ParseFrames(String Data)
{
String[] Frame = Data.split(this.CR);
return Frame;
}
public boolean CheckSumCorrect()
{
String Frame = GetFrameData(this.CommData, 1);
String CalculatedSum = GetCheckSum(Frame);
String FrameSum = GetFrameData(this.CommData, 3);
boolean Status = CalculatedSum.equals(FrameSum);
return Status;
}
public boolean CheckFarmeNum()
{
String FN = GetFrameData(this.CommData, 4);
boolean Status;
if (Integer.toString(this.FrameNo).equals(FN))
{
Status = true;
NextFrameNo();
}
else
{
Status = false;
}
return Status;
}
public String GetCheckSum(String Dat)
{
int x = 0;
for (int i = 0; i < Dat.length(); i++) {
x += Dat.charAt(i);
}
String S = "00" + Integer.toHexString(x % 256);
String CheckSum = S.substring(S.length() - 2).toUpperCase();
return CheckSum;
}
public String GetFrameData(String Data, int FrameType)
{
String Frame = "";
int pos1 = Data.indexOf(this.STX);
int pos2 = Data.indexOf(this.ETX);
int pos3 = Data.indexOf(this.ETB);
if (FrameType == 1)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 1, pos2 + 1);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 1, pos3 + 1);
}
}
else if (FrameType == 2)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 2, pos2);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 2, pos3);
}
}
else if (FrameType == 3)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos2 + 1, pos2 + 3);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos3 + 1, pos3 + 3);
}
}
else if (FrameType == 4) {
Frame = Data.substring(pos1 + 1, pos1 + 2);
}
return Frame;
}
public void sendtoport(String Sample_ID)
{
try
{
int sent = 0;
for (String DataToSend1 : this.DataToSend)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
char c = (char)this.in.read();
String control = String.valueOf(c);
if (control.equals(this.ACK))
{
sent = 1;
}
else if (control.equals(this.NAK))
{
for (int x = 1; x <= this.retries; x++)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
}
sent = 0;
break;
}
}
this.DataToSend.clear();
this.FIndex = 1;
this.out.write(this.EOT);
this.out.flush();
SaveData(this.EOT);
try
{
this.connection2 = DBconnection.getConnection();
String ExecProc = "HK_Update_SCH ?,?,?";
this.connection2.setAutoCommit(false);
this.prepStatement = this.connection2.prepareStatement(ExecProc);
this.prepStatement2.setString(1, Sample_ID);
this.prepStatement2.setString(2, "Access2");
this.prepStatement2.setString(3, "");
this.prepStatement2.executeUpdate();
this.connection2.commit();
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e, "SQLException", 1);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
}
Thread.sleep(10L);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (HeadlessException|InterruptedException e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void SplitFrames(String Frame)
{
int NumSplit = Frame.length() / this.Max_Farme_Size;
for (int i = 0; i <= NumSplit; i++) {
if (i < NumSplit)
{
String part = Frame.substring(i * this.Max_Farme_Size, i * this.Max_Farme_Size + this.Max_Farme_Size);
String IntermdiateFrame = this.STX + this.FIndex + part + this.ETB + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETB).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), IntermdiateFrame);
NextFIndexNo();
}
else
{
String part = Frame.substring(i * this.Max_Farme_Size);
String LastFrame = this.STX + this.FIndex + part + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), LastFrame);
NextFIndexNo();
}
}
}
public void NextFIndexNo()
{
this.FIndex += 1;
if (this.FIndex > 7) {
this.FIndex = 0;
}
}
public void SendOrder(String[] OrderFrame)
{
this.DataToSend.clear();
this.DataToSend.add(0, this.ENQ);
for (int i = 0; i < OrderFrame.length; i++) {
if (OrderFrame[i].length() > this.Max_Farme_Size)
{
SplitFrames(OrderFrame[i]);
}
else
{
String SingleFrame = this.STX + this.FIndex + OrderFrame[i] + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(OrderFrame[i]).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), SingleFrame);
NextFIndexNo();
}
}
}
public void SendOrderData(String SampleData, String TestCodes)
{
HeaderRecord HRec = new HeaderRecord();
PatientRecord PRec = new PatientRecord();
OrderRecord ORec = new OrderRecord();
MessageTerminatorRecord LRec = new MessageTerminatorRecord();
PRec.SetPropertyValue("PracticePatientID", SampleData);
PRec.SetPropertyValue("LabPatientID", SampleData);
PRec.SetPropertyValue("PatientSex", "M");
ORec.SetPropertyValue("SampleID", SampleData);
ORec.SetPropertyValue("ActionCode", "N");
ORec.SetPropertyValue("UniversalTestID", "^^^" + TestCodes.replace(",", "\\^^^"));
ORec.SetPropertyValue("SampleType", "Serum");
ORec.SetPropertyValue("ReportTypes", "O");
String[] records = new String[4];
records[0] = HRec.FormatFrame();
records[1] = PRec.FormatFrame();
records[2] = ORec.FormatFrame();
records[3] = LRec.FormatFrame();
String Msg = HRec.FormatFrame() + PRec.FormatFrame() + ORec.FormatFrame() + LRec.FormatFrame();
System.out.println(">>>>>>>>" + Msg);
try
{
SendOrder(records);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void FramesReady(String[] Frame)
{
}
public void ManageData()
{
try
{
if (this.CommData.contains(this.ENQ))
{
SaveData(this.CommData);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if (this.CommData.contains(this.CRLF))
{
SaveData(this.CommData);
if ((CheckSumCorrect()) && (CheckFarmeNum()))
{
this.TextData += GetFrameData(this.CommData, 2);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if ((!CheckSumCorrect()) || (!CheckFarmeNum()))
{
this.CommData = "";
this.out.write(this.NAK);
this.out.flush();
}
}
else if (this.CommData.contains(this.EOT))
{
SaveData(this.CommData);
String[] x = ParseFrames(this.TextData);
FramesReady(x);
this.TextData = "";
this.FrameNo = 1;
this.CommData = "";
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void Server()
{
try
{
for (;;)
{
char c = (char)this.in.read();
System.out.print(c);
this.CommData += c;
ManageData();
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public static void main(String[] args)
throws Exception
{
switch (Setting.GetPropVal("Socket"))
{
case "TCPIP":
String IP = Setting.GetPropVal("IPaddress");
int Port2Rec = Integer.parseInt(Setting.GetPropVal("INport"));
InetAddress addr = InetAddress.getByName(IP);
String host = addr.getHostName();
Socket s = new Socket(host, Port2Rec);
System.out.println("Connected to :" + host + "/" + Port2Rec);
Access2 TcpChat = new Access2(s);
TcpChat.Server();
break;
case "Serial":
SerialPort serialPort = null;
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement();
if ((portId.getPortType() == 1) &&
(portId.getName().equals(Setting.GetPropVal("ComPort"))))
{
serialPort = (SerialPort)portId.open("HPS", 10);
serialPort.setSerialPortParams(9600, 8, 1, 0);
}
}
System.out.println("Connected to :" + serialPort.getName());
Access2 SerialChat = new Access2(serialPort);
SerialChat.Server();
}
}
}
when i run the program from eclipse
"Wrong Path OR file Lost" is shown
public class Setting
{
public static Properties props;
public static String propVal;
public static String GetPropVal(String param)
{
try
{
props = new Properties();
props.load(new FileInputStream("Access2.ini"));
propVal = props.getProperty(param);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Wrong Path OR file Lost", "Alert", 1);
System.exit(0);
}
return propVal;
}
}
how can i solve that ? It said my class is not found but it exist what is the solution ?

This happens because of improper packaging of class files or rather, improper compilation of Java files inside a package.
Go for a build tool such as Maven with a clean directory including Java files and then generate a .jar.
Basically, if you can, create a fresh Maven or Ant project and create Java files with same names and paste the content into new ones, one by one.
EDIT: Make sure that there is only ONE public class in the main package.

Related

Application becomes irresponsive on InputStream.read();

When the code reaches the InputStream.read(), the application becomes iresponsive.
I think maybe that is the case because the client code runs before the server code and it waits for the input.
Here is the server code
When login button is clicked then the case is "Send login details"(It sends the login details to the client) and if the id and password is correct then the case becomes**"Login successful". It is sending correct value in **output.readUTF();
public void doWork(String line) {
Connection conn = Main.getConnection();
switch (line) {
case "Send login details":
Main main = new Main();
String details = main.giveLoginDetails();
String id = " ";
String password = " ";
int i = 0;
while (details.charAt(i) != ' ') {
id = id + details.charAt(i);
i++;
}
try {
id = id.trim();
password = details.substring(i + 1);
System.out.println(id + " " + password);
output.writeUTF(id + " " + password);
}
catch (IOException e)
{
e.printStackTrace();
}break;
case "Login successful":
String getDet1 = "SELECT * FROM $t;";
if(su == 1)
getDet1 = getDet1.replace("$t", "Post1");
else
getDet1 = getDet1.replace("$t", "Post"+(su*10+1));
System.out.print(getDet1);
rs2 = stmt2.executeQuery(getDet1);
String d;
int dd;
for (int x = 0; x < ch; x++) {
rs2.next();
d = rs2.getString(2);
output.writeUTF(d);
System.out.println(d);
dd = rs2.getInt(3);
output.writeInt(dd);
System.out.println(dd);
d = rs2.getString(4);
output.writeUTF(d);
System.out.println(d);
d = rs2.getString(5);
// if(d == null) {
// output.writeUTF("null");
// System.out.println("null");
// }
// else
output.writeUTF(d);
// System.out.println(d+"not null ");}
}
}
catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
}
}
Client code:- Another scene after the login scene.
It is the Initialize method of Initializable interface. Here i am reading the output but it hangs.
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
String posts = "";
int ch = 0;
Main m = new Main();
Stage stage = m.getStage();
stage.setResizable(true);
int c = 0;
try {
posts = Networking.input.readUTF();
ch = Networking.input.readInt();
}
catch (IOException e)
{
e.printStackTrace();
}
int rs = Integer.valueOf(posts);
for(int k = 0; k<rs; k++) {
c++;
}
try {
Networking.input.readUTF();
}
catch (IOException e)
{
e.printStackTrace();
}
String det = "";
int cl;
for (int i = 0; i < ch; i++) {
a[i].setDisable(false);
a[i].setOpacity(1);
try {
Networking.output.writeUTF("send voting details");
det = Networking.input.readUTF();
System.out.println(det);
cl = Networking.input.readInt();
System.out.println(cl);
det = Networking.input.readUTF();
System.out.println(det);
det = Networking.input.readUTF();
System.out.println(det);
}
catch (IOException exx)
{
exx.printStackTrace();
}
}
}
Add:
Here is my Networking class
package sample;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Networking {
public static ServerSocket serverSocket= null;
public static void connect(int port)
{
try
{
serverSocket = new ServerSocket(port);
System.out.print("Server is started");
while (true)
{
Socket socket = null;
try {
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
Thread thread = new ServerThread(socket, input, output);
thread.start();
System.out.print("Client Accepted");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch(IOException exception)
{
exception.printStackTrace();
}
}
}

SocketTimeoutException in android when trying video streaming

I am trying to make a video streaming application between pc and android device. so I am getting this error "SocketTimeoutException"
private class ChatOperator extends AsyncTask<Void, Void, Void> {
DatagramPacket rcvdp;
DatagramSocket RTPsocket;
int RTP_RCV_PORT = 25000;
Timer timer;
byte[] buf;
final static int INIT = 0;
final static int READY = 1;
final static int PLAYING = 2;
int state;
Socket RTSPsocket;
BufferedReader RTSPBufferedReader;
BufferedWriter RTSPBufferedWriter;
String VideoFileName;
int RTSPSeqNb = 0;
int RTSPid = 0;
final static String CRLF = "\r\n";
int MJPEG_TYPE = 26;
#Override
protected Void doInBackground(Void... params) {
buf = new byte[15000];
int RTSP_server_port = 4444;
String ServerHost = "10.0.3.2";
try {
InetAddress ServerIPAddr = InetAddress.getByName(ServerHost);
VideoFileName = "media/movie.Mjpeg";
RTSPsocket = new Socket(ServerIPAddr, 4444);
RTSPBufferedReader = new BufferedReader(new InputStreamReader(
RTSPsocket.getInputStream()));
RTSPBufferedWriter = new BufferedWriter(new OutputStreamWriter(
RTSPsocket.getOutputStream()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.toString());
}
try {
RTPsocket = new DatagramSocket(RTP_RCV_PORT);
RTPsocket.setSoTimeout(5);
} catch (SocketException se) {
System.out.println("Socket exception: " + se);
System.exit(0);
}
RTSPSeqNb = 1;
send_RTSP_request("SETUP");
if (parse_server_response() != 200)
System.out.println("Invalid Server Response");
else {
state = READY;
System.out.println("New RTSP state: READY");
}
System.out.println("Play Button pressed !");
RTSPSeqNb++;
send_RTSP_request("PLAY");
if (parse_server_response() != 200)
System.out.println("Invalid Server Response");
else {
state = PLAYING;
System.out.println("New RTSP state: PLAYING");
new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
rcvdp = new DatagramPacket(buf, buf.length);
try {
RTPsocket.receive(rcvdp);
RTPpacket rtp_packet = new RTPpacket(rcvdp.getData(), rcvdp.getLength());
System.out.println("Got RTP packet with SeqNum # "
+ rtp_packet.getsequencenumber() + " TimeStamp "
+ rtp_packet.gettimestamp() + " ms, of type "
+ rtp_packet.getpayloadtype());
rtp_packet.printheader();
int payload_length = rtp_packet.getpayload_length();
byte[] payload = new byte[payload_length];
rtp_packet.getpayload(payload);
bmp = BitmapFactory.decodeByteArray(payload,0,payload_length);
System.out.print("a packet recieved");
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Nothing Recieved");
}
}
}, 0, 200);
}
return null;
}
private int parse_server_response() {
int reply_code = 0;
try {
String StatusLine = RTSPBufferedReader.readLine();
StringTokenizer tokens = new StringTokenizer(StatusLine);
tokens.nextToken();
reply_code = Integer.parseInt(tokens.nextToken());
if (reply_code == 200) {
String SeqNumLine = RTSPBufferedReader.readLine();
String SessionLine = RTSPBufferedReader.readLine();
tokens = new StringTokenizer(SessionLine);
tokens.nextToken();
RTSPid = Integer.parseInt(tokens.nextToken());
}
} catch (Exception ex) {
}
return (reply_code);
}
private void send_RTSP_request(String request_type) {
try {
RTSPBufferedWriter.write(request_type + " " + VideoFileName + " "
+ "RTSP/1.0" + CRLF);
RTSPBufferedWriter.write("CSeq: " + RTSPSeqNb + CRLF);
if (request_type.equals("SETUP")) {
RTSPBufferedWriter.write("Transport: RTP/UDP; client_port= "
+ RTP_RCV_PORT + CRLF);
}
else {
RTSPBufferedWriter.write("Session: " + RTSPid + CRLF);
}
RTSPBufferedWriter.flush();
} catch (Exception ex) {
}
}
}
the error is made by this line of code in the timer object
RTPsocket.receive(rcvdp);
I am wondering the same code works well at java SE .
but in android it sends request to the server to run and stop but I cannot receive packets like in java SE . Thanks.

android upd broadcast slow reception

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

Image over socket Java

Im having a problem getting my server to send image over a socket. I need to have 10 1920x1080 images sent to the client in a timecrunch of atleast 5-10 seconds. I seem to get an error anywhere I go or my client/server failsafes go off and make it impossible to send in those certain ways. Could anyone point me in the right direction and tell me a way to implement this without messing up other proccesses?
Client code for nonobject things, and used for UTF packets.
DataInputStream in ;
Client client;
public boolean enabled = true;
Object packet;
String[] tempData;
public Thread thread;
public Data(DataInputStream in , Client client) {
this. in = in ;
this.client = client;
}
#
Override
public void run() {
while (enabled) {
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, mousex = 0, mousey = 0, alpha = 0;
String data = "Invalid";
try {
data = in.readUTF().trim();
} catch(Exception e){
client.comp.printErr("Disconnected from server, " + e.toString());
client.disconnectClient("Socket Closed.");
enabled = false;
}
try{
if (data.contains("id/")) {
data = data.split("id/")[1];
client.id = Integer.valueOf(data);
client.serverHasResponded = true;
client.comp.printOut("Client ID: " + data);
}
if (data.contains("rejected/")) {
data = data.split("rejected/")[1];
//Check to see if server sent packet info;
packet = "null";
try {
if (data.contains("/")) {
tempData = data.split("/");
data = tempData[0];
packet = "null";
for (int i = 1; i < tempData.length; i++) {
if (!packet.equals("null")) {
packet = packet + "/" + tempData[i];
} else packet = tempData[i];
}
}
// Packet info done.
} catch (Exception e) {
client.comp.printErr("Error while splitting packet: " + e.toString());
}
if (Integer.valueOf(data) == 0) {
client.disconnectClient("No Slots Open.");
client.comp.printErr("Rejected from server, no slots open.");
enabled = false;
}
if (Integer.valueOf(data) == 1) {
client.disconnectClient("Invalid Version.");
client.comp.printErr("Rejected from server, invalid version.");
enabled = false;
}
if (Integer.valueOf(data) == 2) {
client.disconnectClient("Kicked.");
client.comp.printErr("Rejected from server, kicked.");
enabled = false;
}
if (Integer.valueOf(data) == 3) {
client.disconnectClient("Unknown Packet.");
client.comp.printErr("Rejected from server, client sent unknown packet on connection? Packet: " + packet);
enabled = false;
}
if (Integer.valueOf(data) == 4) {
client.disconnectClient("Already Logged in.");
client.comp.printErr("Rejected from server, the username " + client.comp.username + " is already logged on?");
enabled = false;
}
if (Integer.valueOf(data) == 5) {
client.disconnectClient("Not Authenticated");
client.comp.printErr("Rejected from server, server requires authentication and were not authenticated?");
enabled = false;
}
if (Integer.valueOf(data) == 6) {
client.disconnectClient("No tick from client.");
client.comp.printErr("Rejected from server, server didnt recieve a tick?");
enabled = false;
}
if (Integer.valueOf(data) == 7) {
client.disconnectClient("No open Canvases.");
client.comp.printErr("Rejected from server, all canvases blacklisted?");
enabled = false;
}
if (Integer.valueOf(data) == 8) {
client.disconnectClient("Banned.");
client.comp.printErr("Rejected from server, Banned.");
enabled = false;
}
}
if(data.contains("servertick/")){
data = data.split("servertick/")[1];
if(Integer.valueOf(data) == client.id){
client.heartbeatManager.serverTicked();
} else {
client.comp.printErr("Server sent an invalid tick.");
}
}
if(data.contains("changeCanvas/")){
data = data.split("changeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
}
if(data.contains("changeCanvasFailed/")){
data = data.split("changeCanvasFailed/")[1];
client.popups.add(new Popup(client, "Error", "Access denied to canvas "+data+"."));
}
if(data.contains("overrideChangeCanvas/")){
data = data.split("overrideChangeCanvas/")[1];
client.currentCanvas = Integer.parseInt(data);
client.comp.printOut(data);
}
if(data.contains("broadcastToClient/")){
data = data.split("broadcastToClient/")[1];
client.chat.addChatMessage(data, Color.white);
}
if (data.contains("chatmessage/")) {
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
user = tokens[0];
if (i == 1)
message = tokens[1];
}
client.chat.addChatMessage(user + ": " + message, Color.white);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
client.canvas[id].draw(x, y, width, height, r, g, b, alpha);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
client.canvas[id].erase(x, y, width, height);
}
if (data.contains("playerjoin/")) {
data = data.split("playerjoin/")[1];
client.chat.addChatMessage(data+" has joined the game.", Color.yellow);
}
if (data.contains("playerleave/")) {
data = data.split("playerleave/")[1];
client.chat.addChatMessage(data+" has left the game.", Color.yellow);
}
} catch (Exception e) {
client.comp.printErr("Failed to process a packet, " + e.toString());
}
}
}
public void close() throws Exception{
thread.stop();
enabled = false;
}
public void setThread(Thread t){
thread = t;
}
Client code ment for images (not modified yet) :
Client client;
DataInputStream in;
Thread thread;
public DataObjects(DataInputStream in, Client c){
client = c;
this.in = in;
thread = new Thread(this);
thread.start();
}
#Override
public void run() {
boolean enabled = true;
while(enabled){
}
}
Server code ment to send/recieve and reroute both UTF and Object packets
public DataOutputStream out;
public DataInputStream in;
public User[] user;
public int slots;
public int id;
InetAddress address;
Server server;
public String username = "";
public boolean enabled;
public boolean ticking;
public boolean allDataSent;
int currentCanvas = 0;
private boolean playerConnected;
public boolean imageByteReady=true;
private boolean sendImage;
public User(DataOutputStream out, DataInputStream in, User[] user, int slots, int i, InetAddress inetAddress, Server server, String username){
this.out = out;
this.in = in;
this.user = user;
this.slots = slots;
this.id = i;
address = inetAddress;
this.server = server;
this.username = username;
ticking = true;
}
#Override
public void run() {
enabled = true;
while(enabled){
try {
String data = in.readUTF();
if(valid(data)){
for(int i = 0; i < slots; i++){
if(user[i]!=null){
if(data.contains("timedout/")){
data = data.split("timedout/")[1];
if(Integer.valueOf(data) == 1){
server.printOut(server.disconnectMessage(id, "Client disconnected because server didnt tick."));
user[id] = null;
enabled = false;
} else {
server.printErr("Got an invalid timeout packet. Packet: timedout/"+data);
}
}
if(data.contains("clienttick/")){
data = data.split("clienttick/")[1];
out.writeUTF("servertick/"+data);
server.packetManager.resetClientWithID(Integer.valueOf(data));
}
if(data.contains("drawcircle/") || data.contains("erasecircle/") || data.contains("chatmessage/"))
user[i].out.writeUTF(data);
}
}
if(data.contains("switchcanvas/")){
data = data.split("switchcanvas/")[1];
if(server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data)) && Integer.valueOf(data) != currentCanvas){
out.writeUTF("changeCanvas/"+data);
currentCanvas = Integer.valueOf(data);
server.printOut(user[id].username+" switched to canvas "+(Integer.valueOf(data)+1));
} else if(!server.canvasaccessmanager.playerCanBeOnCanvas(id, Integer.valueOf(data))){
out.writeUTF("changeCanvasFailed/"+data);
server.printOut(user[id].username+" was denied access to canvas "+(Integer.valueOf(data)+1));
}
}
if(data.contains("sendImage/")){
data = data.split("sendImage/")[1];
sendImage = Boolean.valueOf(data);
}
if (data.contains("drawcircle/")) {
data = data.split("drawcircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, r = 0, g = 0, b = 0, id = 0, alpha = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 4)
r = Integer.valueOf(tokens[i]);
if (i == 5)
g = Integer.valueOf(tokens[i]);
if (i == 6)
b = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
if (i == 8)
alpha = Integer.valueOf(tokens[i]);
}
server.canvasManager.drawCircle(x, y, width, height, r, g, b, alpha, id);
}
if (data.contains("erasecircle/")) {
data = data.split("erasecircle/")[1];
String[] tokens = data.split("/");
int x = 0, y = 0, width = 0, height = 0, id = 0;
for (int i = 0; i < tokens.length; i++) {
if (i == 0)
x = Integer.valueOf(tokens[i]);
if (i == 1)
y = Integer.valueOf(tokens[i]);
if (i == 2)
width = Integer.valueOf(tokens[i]);
if (i == 3)
height = Integer.valueOf(tokens[i]);
if (i == 7)
id = Integer.valueOf(tokens[i]);
}
server.canvasManager.eraseCircle(x, y, width, height, id);
}
if(data.contains("chatmessage/")){
data = data.split("chatmessage/")[1];
String[] tokens = data.split("/");
String user = "";
String message = "";
for (int x = 0; x < tokens.length; x++) {
if (x == 0)
user = tokens[0];
if (x == 1)
message = tokens[1];
}
server.printOut(user + " said '" + message+"'");
}
} else {
server.printErr("Caught an overlapped packet from client "+id);
server.packetManager.resetClientWithID(id);
}
} catch (IOException e) {
if(enabled){
server.printOut(server.disconnectMessage(id, "Client socket closed. Manual disconnect?"));
user[id] = null;
enabled = false;
}
}
}
saveUserData();
if(playerConnected)
sendLeaveMessage();
}
private boolean valid(String data) {
String[] tokens = data.split("/");
if(tokens[1].toLowerCase().contains(inputFix(tokens[0]))){
return false;
}
return true;
}
private String inputFix(String data) {
return data.replaceAll("[^a-zA-Z]", "").toLowerCase().trim();
}
private void saveUserData() {
server.playermanager.setUserProperty(username, "currentCanvas", String.valueOf(currentCanvas));
}
public void sendID() {
try {
out.writeUTF("id/"+id);
playerConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendCanvases() {
try{
sendCanvas(0);
server.printOut("Sent canvas 0");
Thread.sleep(1);
} catch(Exception e){
server.printErr("Failed to send canvas 0");
sendCanvases();
}
}
public void sendCanvas(int id) throws Exception{
}
public void sendLeaveMessage(){
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerleave/"+username);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
public void sendJoinMessage() {
for(int i = 0; i < slots; i++){
if(i != id){
if(user[i] != null){
try {
user[i].out.writeUTF("playerjoin/"+username);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public void sendData() {
if(server.playermanager.userExists(username)){
int x = Integer.parseInt(server.playermanager.loadUserProperty(username, "currentCanvas"));
currentCanvas = x;
try {
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//If user is new;
int x = server.canvasaccessmanager.nextOpenCanvas(username);
try {
currentCanvas = x;
out.writeUTF("overrideChangeCanvas/"+x);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setUpUserData() {
if(!server.playermanager.userExists(username)){
server.playermanager.createUser(username);
}
}
Client code:
public Dimension dimension;
static final long serialVersionUID = 1L;
public Thread thread;
public int currentfps;
public long start;
public int fps;
static Socket socket;
public static DataInputStream in ;
public Listener listener = null;
public boolean isRunning = true;
public boolean justClicked;
public static int canvasMax = 10;
public Canvas[] canvas = new Canvas[canvasMax];
public int currentCanvas;
public Graphics canvasGraphics;
public Player player;
public DataOutputStream out;
public boolean connectedToServer = false;
public boolean click;
public int id;
public Image screen;
public static Toolkit toolkit = Toolkit.getDefaultToolkit();
public static Image cursor = toolkit.getImage("res/icons/cursor.png");
public static Image tabCanvas = toolkit.getImage("res/image/tabs/tabCanvas.png");
public static Image tabColor = toolkit.getImage("res/image/tabs/tabColor.png");
public Image tabGuide = toolkit.getImage("res/image/tabs/tabGuide.png");;
public static Image[] guideImages = new Image[canvasMax];
public int tabOffset = 0, tabWidth = 200, currentTabWidth = 0, tabHeight = 0;
public boolean ChatOpen;
public CanvasGUI canvasgui;
public int currentColor;
public int colorMax = 10;
public boolean serverHasResponded = false;
public int wait;
public Data data;
public Chat chat;
public int defaultPort = 58828;
public int port = 0;
public String ip = "";
public ColorGUI colorgui;
public GuideGUI guidegui;
public int currentGuide;
public int waitMax = 1000000;
public HeartbeatManager heartbeatManager;
public ArrayList<Popup> popups;
public Integer lastCanvasClick;
private boolean debug;
public ServerLogin serverLogin;
public boolean serverLoginOpen;
public Component comp;
int index;
public boolean started;
private boolean disconnecting;
public boolean clientHasRecieved;
public Client(Component component) {
this.comp = component;
}
public void connectClient(String ip, int port) {
try {
this.ip = ip;
this.port = port;
socket = new Socket(ip, port);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
connectedToServer = true;
out.writeUTF("authenticate/" + comp.authenticated);
out.writeUTF("username/" + comp.username);
out.writeUTF("version/" + comp.version);
data = new Data( in , this);
Thread thread = new Thread(data);
data.setThread(thread);
thread.start();
DataObjects dataObjects = new DataObjects(in, this);
} catch (Exception e) {
comp.printErr("Failed to connect to server, " + e.toString());
disconnectClient("Failed to connect");
}
}
public void disconnectClient(String var1) {
if(!disconnecting){
disconnecting = true;
try {
in = null;
out = null;
if (data != null){
data.enabled = false;
data = null;
};
if(connectedToServer)
socket.close();
socket = null;
connectedToServer = false;
serverHasResponded = false;
wait = 0;
String str = "Disconnected from server "+ip+":"+port+", "+var1;
comp.printOut(str);
ip = "";
port = 0;
comp.stopGame();
comp.startWarningMenu(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
void initializing(int i) {
index = i;
comp.printOut("Index: "+i+".");
tabHeight = comp.height;
isRunning = true;
comp.printOut("Creating Canvases.");
for (int x = 0; x < canvasMax; x++) {
canvas[x] = new Canvas(this);
canvas[x].clear(0, 0, comp.width, comp.height);
comp.printOut("Creating Canvas"+(x+1)+".");
}
comp.printOut("Canvases Created.");
comp.printOut("Loading Guides.");
for (int x = 0; x < guideImages.length; x++) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_" + x + ".png");
if (!new File("res/image/guides/guides_" + x + ".png").exists()) {
guideImages[x] = toolkit.getImage("res/image/guides/guides_0.png");
comp.printErr("Couldnt Locate Guide"+(x+1)+".");
} else {
comp.printOut("Loaded Guide"+(x+1)+".");
}
}
colorgui = new ColorGUI(this);
comp.printOut("Loaded ColorGUI.");
guidegui = new GuideGUI(this);
comp.printOut("Loaded GuideGUI.");
chat = new Chat(this);
comp.printOut("Loaded Chatting Class.");
popups = new ArrayList<Popup>();
comp.printOut("Loaded ArrayList<Popup>.");
currentCanvas = 0;
heartbeatManager = new HeartbeatManager(this);
comp.printOut("Loaded Heartbeat Manager.");
canvasgui = new CanvasGUI(this);
comp.printOut("Loaded CanvasGUI.");
screen = comp.createImage(comp.pixel.width, comp.pixel.height);
comp.printOut("Loaded Screen Component.");
player = new Player(this);
comp.printOut("Loaded Player Class.");
serverLogin = new ServerLogin(this);
comp.printOut("Loaded Server Login GUI.");
started = true;
comp.printOut("Starting Threads. Game Loading done!");
thread = new Thread(this);
thread.setPriority(6);
thread.start();
}
Looks like a case for buffering to get better throughput. I see you instantiating DataInputStream/DataOutputStream, but those aren't buffered so I think you could get a big boost by adding BufferedInput/OutputStream to each side. I don't see your code where you copy the image to the stream. So the following should help:
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
Just remember to flush(). The other option you can do is compress your data before sending it over the stream. If you are sending a 1920x1080 image uncompressed would be around 8MB (=1920px * 1080px * 4 bytes / pixel) so 5-10s is not a surprising. Adding a GZipInputStream on top of that is pretty simple, and would compress all data sent. Image specific compression would probably achieve a higher compression, but more involved.

program to show a progress bar while transferring all files from one server to another in java

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...

Categories