I need to send serialized Data from an Android Device to a Java Server.
I don't know why, but the communication seems to be very unstable. In the Debugger, the java.io.StreamCorruptedException: is thrown immediately after the start. not one Object is passing.
Without the debugger, nearly 10 Messages are passed until the same Exception is thrown.
Anyone got an idea, please help me:)
Thank you!
Fabian
Exception:
java.io.StreamCorruptedException: invalid type code: 2F
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at androidAnbindung.AndroidVerwalter.run(AndroidVerwalter.java:114)
java-code:
public void Nachrichtenaustausch(){
port ++;
try {
serverSocket = new java.net.ServerSocket(port);
System.out.println("Warte auf 2. Verbindungsaufbau...");
client = serverSocket.accept();
System.out.println("Verbindung 2 ist eingegangen...");
in = new ObjectInputStream(new ObjectInputStream(client.getInputStream()));
Nachricht n;
// starte den regulären Verkehr mit dem Androidgerät
new Thread(this).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
Nachricht speicher;
while (true) {
try {
speicher = (Nachricht) in.readObject();
if (speicher != null) {
System.out.println(speicher.getName()+"..............................."+speicher.getWerte().get(0));
}synchronized (objekliste) {
for (AndroidObject ao : this.objekliste) {
if (speicher.getName().equals(ao.name)) {
ao.abstrakter_Wert = speicher.getAktuellerWert();
if (speicher.getWerte()!=null) {
ao.werte = speicher.getWerte();
}
}
}
}
Thread.sleep(50);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
}
}
}
and the android thread:
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if (!nachrichtenliste.isEmpty()) {
Nachricht speicher = nachrichtenliste.get(0);
try {
out.writeObject(speicher);
out.flush();
synchronized (nachrichtenliste) {
nachrichtenliste.remove(speicher);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thread.sleep(50);
handler.post(this);
}
} catch (Exception e) {
// TODO: handle exception
}
}
I can imagine that Android and Java are not exactly serialization compatible here. So that one side sends a code that the other does not expect.
I'd rather go with some more textual protocol (json, xml) here, than with serialization.
Related
I am creating a game where in the client I am supposed to get some arrays from a server and reveal them into the screen. I can press the button X times to get X arrays.
Currently I am using this code
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDice();
try {
int[] tempArray = new GetDiceTask().execute(socket).get();
printDice(tempArray,pDice);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but if I don't like this array and I want another one I cannot use the AsyncTask cause I get the common error for Cannot execute task: the task has already been executed (a task can be executed only once).
This is my code for AsyncTask.
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Is there a way that I can take multiple arrays without that exception?
I am trying to send a file using Android bluetooth sockets. I am getting the pairing requests but unfortunately the data is not being transferred
my Server side and client side is as follows:
Server: (for my application server is receiving the data)
public void run() {
super.run();
BluetoothAdapter mBtadapter = BluetoothAdapter.getDefaultAdapter();
Log.i("bluetooth Adapter", "got adapter "+ mBtadapter.getAddress());
try {
Ssocket = mBtadapter.listenUsingRfcommWithServiceRecord("CardXchange", uuid);
Log.i("Socket", "Socket Acquired "+ Ssocket.toString());
} catch (IOException e) {
e.printStackTrace();
}
while(true){
if(read_flag()==1){
try {
Toast.makeText(c, "flag is eventually 1", Toast.LENGTH_LONG).show();
Ssocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
try {
client_socket = Ssocket.accept();
if(client_socket!=null){
//this function is used to handle the connection when sockets get connected
manageConnection1(client_socket);
Ssocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("breaked ", "oh god!! out of the loop ");
}
//implementation of the function
private void manageConnection1(BluetoothSocket client_socket2) {
// TODO Auto-generated method stub
int bytes;
Log.i("serevr chya manage connection madhe gela", "in servers manage connection ");
File file = new File("/sdcard/myfolder/received.Xcard");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
InputStream is = client_socket2.getInputStream();
while((bytes = is.read(buffer, 0, 1024))>0){
fos.write(buffer, 0, 1024);
}
is.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
client_socket2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and the client side (the sending side is like this):
public void run(){
try {
Method m = send_dev.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
Csocket = (BluetoothSocket) m.invoke(send_dev, 1);
Csocket.connect();
manageSendConnection(Csocket);
}catch(Exception e){
e.printStackTrace();
}
}
//function to handle after connection is established.
private void manageSendConnection(BluetoothSocket csocket) {
// TODO Auto-generated method stub
File f = new File("/sdcard/myfolder/card3.Xcard");
byte[] buffer = new byte[(int)f.length()];
try {
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(buffer, 0, (int)f.length());
OutputStream os = csocket.getOutputStream();
os.write(buffer);
os.close();
fis.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
csocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the pairing request but the data is not being sent.
can anyone please help me to find the problem and give a hint on solution??
Error:
android.security.KeyChainException: java.lang.IllegalStateException: uid 10111 doesn't have permission to access the requested alias
Code:
new Thread(new Runnable() {
public void run() {
try {
X509Certificate[] myCertificates=KeyChain.getCertificateChain(MainActivity.this, "ServerCertificate");
if(myCertificates!=null)
{
System.out.println("myCertificates size "+myCertificates.length);
for(int i=0;i<myCertificates.length;i++)
{
System.out.println("myCertificates i= "+i+" "+myCertificates[i]);
}
}
} catch (KeyChainException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
The KeyChain class requires the application to call choosePrivateKeyAlias() at least once after the application is installed before calling getPrivateKey() or getCertificateChain(). So even if one knows the alias beforehand, the choosePrivateKeyAlias() must be called at least once, otherwise there is no trust established between the app and the internal database that KeyChain uses.
I am a new in android developing, I've code to connect to server and send commands,
How to separate connection code in method and sending code in another method.
my code as following:
public void onClick(View arg0) {
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
// connect code
socket = new Socket("172.16.149.64", 8888);
// sending code
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Write a class of your own and make the Socket one of its member variables. You can then write connect() and sendData() methods to your class using the same socket in both methods.
My original goal is to build my own modal dialog. At some point, I have to run an inner loop, which would do really close to what GetMessage/PostMessage do in Win32, if you got Win32 experience then you are quite familiar with this. The inner loop will block current workflow but still process events. The pseudo code would be like,
private void doModal() {
doSth();
// start loop and process events
while (!isQuit) {
Message msg = nextMessage();
// process all wanted msgs, and simply discard all unexpected msgs
if (isWantedMsg) {
sendToTarget(msg);
}
}
}
I've looked into source code, Looper.loop(), which was,
public static final void loop() {
Looper me = myLooper();
MessageQueue queue = me.mQueue;
while (true) {
Message msg = queue.next(); // might block
if (msg != null) {
if (msg.target == null) {
// No target is a magic identifier for the quit message.
return;
}
msg.target.dispatchMessage(msg);
msg.recycle();
}
}
}
Basically I'd like to write such a loop, then I'm able to receive all msgs and process or drop them accordingly. Unfortunately, MessageQueue belongs to package android.os, I have no privilege to access most of its interfaces. Activity.dispatchTouchEvent is just a handler, not my case.
How could I do? Thanks.
==========================SOLUTION=====================================
I solved it by reflection, I exactly copied source of Looper.loop(), see below,
private void startModal() {
Class clsMsgQueue = null;
Method nextMethod = null;
Class clsMsg = null;
mQuitModal = false;
MessageQueue queue = Looper.myQueue();
clsMsgQueue = queue.getClass();
try {
nextMethod = clsMsgQueue.getDeclaredMethod("next", new Class[]{});
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nextMethod.setAccessible(true);
while (!mQuitModal) {
Message msg = null;
try {
msg = (Message)nextMethod.invoke(queue, new Object[]{});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (msg != null) {
clsMsg = msg.getClass();
Field targetFiled = null;
try {
targetFiled = clsMsg.getDeclaredField("target");
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
targetFiled.setAccessible(true);
Handler target = null;
try {
target = (Handler) targetFiled.get(msg);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (target == null) {
// No target is a magic identifier for the quit message.
mQuitModal = true;
}
target.dispatchMessage(msg);
msg.recycle();
}
}
}
When dialog was dismissed, mQuitModal was set to true either.
If don't care much about performance issue, it worked.
Sorry, Android deliberately does not support nested event loops like this. You just will have to structure your code a different way -- for dialogs you will typically start the dialog, return to the event loop, and implement callbacks to handle the result from it.