I'm writing a small app that's supposed to mirror moves made on another phone during a game of tetris. It works perfectly for a little while, untill i get a CorruptedStreamException on the server side while writing an object.
Here's the code for the server:
public void run() {
ServerSocket ss = null;
Socket s = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try{
ss = new ServerSocket(PORT);
s = ss.accept();
Log.i(TAG,"accepted");
oos.flush();
ois = new ObjectInputStream(s.getInputStream());
while(run){
busy=true;
oos.writeObject(positions);
busy = false;
this.sleep(100);
oos.reset();
}
} catch (Exception e) {
e.printStackTrace();
}finally{//close sockets!!
try{
ois.close();
oos.close();
s.close();
ss.close();
}catch(Exception e){}
}
}
I'll toss out the client side code too:
public void run() {
Canvas c = null;
Socket s = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
Log.i(TAG, "it entered try");
s = new Socket(IP, PORT);
oos = new ObjectOutputStream(s.getOutputStream());
oos.flush();
ois = new ObjectInputStream(s.getInputStream());
Log.i("try","has connected");
while(run){
blockList=(ArrayList<Posision>)ois.readObject();
if(blockList!=null){
try{
c=mSurfaceHolder.lockCanvas(null);
synchronized(mSurfaceHolder){
mTetrisView.drawTetris(c, blockList);
}
}finally{
if(c!=null){
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}catch (EOFException ez){
Log.i("catch", "End of file");
} catch (Exception e) {
Log.i("catch",e.getMessage());
e.printStackTrace();
}finally{//close socket!!
try{
ois.close();
oos.close();
s.close();
}catch(IOException e){}
}
}
And a stack trace might come in handy too, when thinking of it:
java.io.StreamCorruptedException
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1712)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1665)
at com.prosjekt.tetris2.ServerThread.run(ServerThread.java:42)
Now why am I getting this error? As far as I know, writeObject() shouldn't be able to throw it.
I'm not really sure how I figured this out, but turns out that the client thread didn't print the errors it got (this however, doesn't explain why the server side threw the corruptedStreamException). The fault lay with the client getting a OptionalDataException with the length field set to 0 (indicates end of stream). I knew for a fact that the writeObject were called often enough that this shouldn't be a problem, so I decided to rewrite part of the code.
The final fix is really too simple, and this is how my while loop at server side looked like after rewriting:
while(run){
oos.writeObject(new ArrayList<Posisions>(positions));
oos.flush();
}
There's viritually no changes to the client side, so I guess the rate of resets() somehow stomped the stream.
Related
Below is a snippet of my code on generating signature:
File file = new File("privatekey.pkcs8");
FileInputStream fis = new FileInputStream(file);
pemBytes = new byte[fis.available()];
fis.read(pemBytes);
fis.close();
File filedata = new File("hi");
FileInputStream fis2 = new FileInputStream(filedata);
dataBytes = new byte[fis2.available()];
fis2.read(dataBytes);
fis2.close();
} catch (Exception e) {
e.printStackTrace();
}
PrivateKey privKey=null;
try {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pemBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
privKey = kf.generatePrivate(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
/* Create a Signature object and initialize it with the private key */
byte[] realSig = null;
try{
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privKey);
signature.update(dataBytes);
realSig = signature.sign();
byte[] res = Base64.encodeBase64(realSig);
FileOutputStream sigfos = new FileOutputStream("mysignature");
sigfos.write(res);
sigfos.close();
} catch (Exception e) {
e.printStackTrace();
the signature works fine but currently I would like to implement a time stamp function which will cause the signature to expire after sometimes, perhaps 30 days. However, I have no experience dealing with time stamp, I was also unable to find example or tutorials which explain well enough.
Therefore, I would like to ask for links/explanation/tutorial on how to get started!
And if possible, snippet of codes that I could use!
Thanks in advance!
Situation: : I must either send a parameter to the server, or a serialized object. It can be in any random order.
What I've done: As per this post, I developed a protocol to let the server know what I'm sending just before I actually send it. If its any string, it just goes via PrintWriter.println().
But just before sending a serialized object via ObjectInputStream, I send a PrintWriter.println("O"). So the server knows it must expect a serialized object next.
Problem: I'm getting the StreamCorruptedException, even though I'm using only one instance of ObjectInputStream at the client throughout the socket's life. Should anything be done at the Server end ?
----------------------- EDITED BELOW ---------------------
Client End:
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(thisSocket.getOutputStream())),
true);
if (!sent){
out.println("Dummy");
sent = true;
}
objectOutputStream.flush();
objectOutputStream.reset();
out.println("#SerialO#"); //This param signals the server
//that an object will be sent next.
if(((calcSum) this.obj).getRemotable()){
/*objectOutputStream.flush();
objectOutputStream.reset();*/
Log.i("ENDPOINT", "Sending Serialized data ...");
objectOutputStream.writeObject(this.obj);
objectOutputStream.flush();
objectOutputStream.reset();
// Get the byte array
byte[] byteArray = byteArrayOutputStream.toByteArray();
}
Server End:
while (!Thread.currentThread().isInterrupted()) {
try{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
// NOW DECLARED AND USED IN UpdateUIThread
//PrintStream out = new PrintStream(socket.getOutputStream());
if(!sent)
{
flg = this.input.readLine().toString();
Log.i("SERVER","SERVER Received False flg as "+flg);
sent = true;
}
else{
flg = this.input.readLine().toString();
System.out.println("SERVER Received flg as "+flg);
if(flg.contains("#SerialO#")){ //Be prepared to
// receive a serilized obj from client
//Log.d("SERVER","Received an object");
CommunicationThread commThread = new CommunicationThread(this.clientSocket,it);
new Thread(commThread).start();
}
else
{
//Log.d("SERVER","Received a parameter "+flg);
executor = Executors.newFixedThreadPool(5);
executor.execute(new updateUIThread(this.clientSocket,flg));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("SERVER", "Creation went bad -- "+e.toString());
break;
}
catch (Exception e)
{
Log.d("CLIENT TAG", "Creation went bad -- "+e.toString());
}
}
}
...
public CommunicationThread(Socket clientSocket, Intent it) {
this.clientSocket = clientSocket;
try {
Log.d("SERVER","Inside Server's Comm Thread");
if (mInput==null){
Log.i("SERVER","Receiving very first serialized obj");
mOutput = new ObjectOutputStream(this.clientSocket.getOutputStream());
System.out.println("Inside Server's Comm Thread 2 ");
// EXCEPTION OCCURS IN THE LINE BELOW.
mInput = new ObjectInputStream(new BufferedInputStream(this.clientSocket.getInputStream()));
}
You can't mix streams and readers/writers on the same socket if any of them is buffered. In this situation I would use the object stream for everything.
I am trying to receive port based SMS with the below piece of code.
serverSocket = new ServerSocket(SERVERPORT);
Socket client = serverSocket.accept();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
System.out.println("Reading Line is>>>>>>>>>>>>>"+line);
break;
}
} catch (Exception e) {
System.out.println("Exception While Reading SMS>>>>>>>>>>"+e);
}
Will it wait in the line of serverSocket.accept(); until it gets the port based SMS,Is this correct behaviour or I am making any issue which hangs at that place.I am not able to move beyond it.
I am not able to test fully,I am not having option of testing it here,sending the port message.
Did anyone came across this issue.Any Info regarding this will be useful.
I think you could try adding the while statement
serverSocket = new ServerSocket(SERVERPORT);
while(true){
Socket client = serverSocket.accept();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
line = null;
while ((line = in.readLine()) != null) {
Log.d("ServerActivity", line);
System.out.println("Reading Line is>>>>>>>>>>>>>"+line);
break;
}
} catch (Exception e) {
System.out.println("Exception While Reading SMS>>>>>>>>>>"+e);
}
}
and for as long as it's true, it will wait for the client to send a message. It's been a while since i last did one of these Working with Datagrams
i am thinking about there are some many way to store data in file , i found one of this is useing buffedinputstream ,but i really don't know is it good ??
if i using like this , it will be most fast ??
is there any other suggestion ?? i just want make the file io more fast !!
public ArrayList<String> testReadingTxtFromFile(){
ArrayList<String> result = null;
try {
FileInputStream fIn = openFileInput("cacheingtext.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader reader = new BufferedReader(isr);
String line;
while((line = reader.readLine() )!= null){
String[] datas = line.split(",");
Log.i("check", datas.length+"");
for(String data:datas){
Log.i("check", data);
result.add(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void testWritingTxtToFile(String[] messages){
try {
FileOutputStream fo = openFileOutput("cacheingtext.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fo);
BufferedWriter writer = new BufferedWriter(osw);
int size = messages.length;
for(int i=0;i<size;i++){
writer.write(messages[i]);
writer.write(",");
Log.i("check", "write "+messages[i]);
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.
Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.
What I see in your case is that you are using a byte-oriented Stream.
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
So,if you want to generally deal with Characters (reading text files), go for Character-oriented Stream(Reader/Writer). But if you want to process the content independent of what type of file is it, go for byte-oriented stream.
I have an OpenGL game with two images, one is a texture atlas, and one is a single image. When I try to open the single one to an OpenGL object the application dies when closing it.
The code:
InputStream is = context.getResources().openRawResource(texture);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
is = null;
Log.i("log", "try");
} catch (IOException e) {
Log.i("log", "Catch");
}
}
It decodes the InputStream, but it steps into the catch after closing. I really can't understand what is the problem. Opening and closing InputStreams with the other texture works fine.
try the below code to print a stacktrace
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
ex.printStackTrace(printWriter);
String stacktrace = result.toString();
Log.i("log", "Catch" + stacktrace);
then hopefully you will have your answer :)