Results 1 to 4 of 4
Thread: StreamCorruptedException
- 10-27-2010, 03:49 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
StreamCorruptedException
hi i'm doing a simple MultiThreadedServer. the problem i got that the client has to send a nickname to the server, the server checks doesnt exists such nick, then creates a key for the client and sends the nick and key to the client. then the client has to print it out.
the problem is that the client doesn't print out the key and nick that recives
form the server. it shows this error:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at p3.ChatClient.run(ChatClient.java:69)
if someone can help me with this please. shure it is a silly thing
before i used datainputsstream and dataoutputstream instead of ObjectInputStream and ObjectOutputStream and worket perfectly
here is the servercode:
and here the client code:Java Code:import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; /** * * @author Ricard Santafé y Dani Garcia *clase proporcionada en clase e implementada para que haga lo mismo que en la actividad1 pero mediante multithread */ public class MultiThreadedServer extends Thread { public void run() { try { ServerSocket socket = new ServerSocket(); socket.bind(new InetSocketAddress("localhost", 10001)); while (true) { final Socket connection = socket.accept(); new Thread() { public void run() { try { handleRequest(connection); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }.start(); } } catch (IOException e) { e.printStackTrace(); } } private void handleRequest(Socket connection) throws IOException { //DataOutputStream dos; //DataInputStream dis; ObjectInputStream ois; ObjectOutputStream oos; boolean bool=true; Object juas=null; String aviam=null; List a = new ArrayList(); List b= new ArrayList(); int z, x; Socket sockero= connection; ois= new ObjectInputStream(sockero.getInputStream()); System.out.println("SERVIDOR: conexion establecida con cliente");//print informativo oos= new ObjectOutputStream(sockero.getOutputStream()); //dos= new DataOutputStream(sockero.getOutputStream()); while(bool==true)//mientras bool sea true { //dis= new DataInputStream(sockero.getInputStream());//socket dos obten datos procedentes de connection try { juas=ois.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } aviam=(String) juas; //aviam=dis.readUTF();//guardar informacion string recibida en string if(a.isEmpty() || !a.contains(aviam))//si la liasta este vacia o no contenga el nick { a.add(aviam);//añado string a la lista bool=false;//rompo la condicion del bucle oos.writeObject("1"); //z=1;//int de permiso aceptado para cliente referente al nick //dos.writeInt(1);//escribir numero de permiso en socket de salida } else//si no { try { sleep(500);//duerme por 0.5s } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } oos.writeObject("0"); //z=0;//permiso a 0= a denegar permiso de nick //dos.writeInt(0);//escribir dicha informacion en el socket de salida } } while(bool==false)//mientras nick aceptado { x=(int) Math.floor(Math.random()*10000);//funcion que genera un entero aleatorio entre 0 y 9999 if(b.isEmpty() || !b.contains(aviam+x))//si lista esta vacia o no contiene nick+contraseña { try { sleep(500);//duerme por 0.5s } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } bool=true;//rompo condicion del while b.add(aviam+x);//annado aviam+pasword a la lista System.out.println("SERIDOR: cliente "+aviam+" le ha tocado de pass "+x); oos=new ObjectOutputStream(sockero.getOutputStream()); oos.writeObject(x); //dos= new DataOutputStream(sockero.getOutputStream());//prodeco a preparar el socket de salida para escribirle informacion //dos.writeInt(x);//escribo en socket el numero de password oos.close(); ois.close(); sockero.close();//cirro conexion con el cliente ya que no debo de hacer nada mas con el } } if(bool==false) bool=true; } public static void main(String[] args) { MultiThreadedServer mts = new MultiThreadedServer(); mts.start(); } }
Java Code:import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; /** * * @author Ricard Santafé y Dani Garcia *clase cliente envia posible nick recibe permiso hasta cumplir con el entonces recibe contraseña */ public class ChatClient extends Thread implements Cloneable { String nick;//string donde se guarda la informacion del cliente String bool;// integer permiso de aceptacion de nick boolean aviam=true;//boolean para while de comprobacion ni nick ObjectInputStream ois; Object auxx; ObjectOutputStream oos; //private DataInputStream in;//socket de entrada //private DataOutputStream dos;//socket de salida private String pass;//string generado para nick char[] elementos={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z'};//posibles chars que se pueden generar en el string nick public void run()//parte run { try { Socket socket = new Socket("localhost",10001);//crear socket que escuche el puerto 10001 de host "localhost" while(aviam==true)//while para comprobar disponibilidad de nick { nick=generaString();//lee nick try { oos= new ObjectOutputStream(socket.getOutputStream()); ois= new ObjectInputStream(socket.getInputStream()); oos.writeObject(nick); } catch(EOFException er) { er.printStackTrace(); } //dos= new DataOutputStream(socket.getOutputStream());//preparo socket de salida para escribir en dicho socket //dos.writeUTF(nick);//escribo en socket de salida el nick try { auxx=ois.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } bool=auxx.toString(); //in = new DataInputStream(socket.getInputStream());//preparo socket de entrada para leer comprobacion de nick //bool=in.readInt();//leo el permiso if(bool.equals("1"))//si permiso es aceptado { aviam=false;//romper condicion del while } else//si no System.out.println("CLIENTE:el nick se encuentra en uso porfavor utilice otro nick");//printf informativo } try { auxx=ois.readObject(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("CLIENTE: Soy "+ nick+ " y Server me ha dado de pass "+auxx);//printf informativo oos.close(); ois.close(); socket.close();//cerrar ssocket } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException el) { el.printStackTrace(); } } public String generaString()//funcion que genera un string aleatorio { char[] conjunto= new char[8];// array de chars de size 8 for(int i=0;i<8;i++)// for de 8 iteraciones de 0 ... 7. por cada iteracion { int el = (int)(Math.random()*elementos.length);//obten numero aleatorio entre 0 y size elementos-1.guardarlo en "el" conjunto[i] = (char)elementos[el];//annade al arreglo "conjunto" el char que hay en la posicion "el" del arreglo elementos } return pass = new String(conjunto);//guardar el resultado del bucle en string pass para retornarlo } public static void main(String[] args) { ChatClient cc= new ChatClient(); cc.start(); } }
- 10-27-2010, 05:50 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,373
- Blog Entries
- 7
- Rep Power
- 17
You're using two ObjectOutputStreams in your server. When such a stream is opened it always writes a header block first so your client receives two of those headers while it only expects one in its single ObjectInputStream; hence the stream corrupt exception.
kind regards,
Jos
- 10-28-2010, 01:02 AM #3
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
thx JosAH the problem was that and now it works perfectly.
very kind of you to spare some of your time with my problems
- 10-28-2010, 07:16 AM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,373
- Blog Entries
- 7
- Rep Power
- 17
Cool; if you look at the API documentation for the ObjectOutputStream you can see the protected method writeStreamHeader(); that's the one that writes the header block to the stream. I've seen suggestions to override that class and that method; the method is supposed to do nothing in the extended class. Don't do that because people don't realize that they can only use that class as a second or third etc. class in a row.
kind regards,
Jos
Similar Threads
-
I got a problem with StreamCorruptedException, any ideas?
By Goodwine in forum New To JavaReplies: 8Last Post: 11-05-2010, 10:26 PM -
Trouble resolving a StreamCorruptedException
By tim in forum New To JavaReplies: 0Last Post: 07-22-2009, 10:10 PM -
StreamCorruptedException
By cristo_haris in forum Advanced JavaReplies: 11Last Post: 04-20-2009, 03:44 PM -
StreamCorruptedException and Casting troubles
By Wassa in forum NetworkingReplies: 2Last Post: 02-18-2009, 03:07 PM -
java.io.StreamCorruptedException
By elizabeth in forum Advanced JavaReplies: 1Last Post: 08-06-2007, 06:45 PM


LinkBack URL
About LinkBacks


Bookmarks