Panait Valentin February 2016

Need help on a simple server/multiple client chat application

this is the scenario .. i have 2 clients connected to a server.. i want them to be able to chat with eachother. After a couple of messages i get this error.

    Exception in thread "Thread-0" java.lang.ClassCastException:
    java.io.ObjectStreamClass cannot be cast to message.Mesaj
    at server.ServerThread.readAndWrite(ServerThread.java:43)
    at server.ServerThread.run(ServerThread.java:61)
    java.io.StreamCorruptedException: invalid type code: 00
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at server.ServerThread.readAndWrite(ServerThread.java:43)
    at server.ServerThread.run(ServerThread.java:61)

This is the client:

package client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import message.Mesaj;

public class Client {

public static int port=4321;
public static Socket socket;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Scanner sc;

public Client() throws IOException{
    socket = new Socket ("localhost",4321);
    oi = new ObjectInputStream(socket.getInputStream());
    oo = new ObjectOutputStream(socket.getOutputStream());

}


public static void listen() throws ClassNotFoundException, IOException{
    while(true){
        Mesaj m = (Mesaj) oi.readObject();
        if(m!=null){
            System.out.println("mesajul este: " + m.getMesaj());
        }
    }
}

public static void write() throws IOException{
    sc= new Scanner(System.in); 
    while(true){
        String trimite= sc.nextLine();
        Mesaj m = new Mesaj();
        m.setMesaj(trimite);

        oo.writeObject(m);
        oo.flush();

    }

}


public static Thread t = new Thread(){
    public void run(){

        try {
            listen();
        } catch (ClassNotFoundException | IOException e) {
                    

Answers


Ferrybig February 2016

You having concurrency issues.

Both serverthreads access the same static outputstream, meaning that there is a change for corruption as Object streams aren't designed for this.

In ServerThread, remove static from all the variables and the method "readAndWrite".

public ObjectOutputStream oo;
public ObjectInputStream oi;
public Mesaj m;
public Socket socket;
...
public void readAndWrite() throws ClassNotFoundException, IOException{

If you want to access the output streams from multiple threads, you should synchronize on them.

Post Status

Asked in February 2016
Viewed 2,680 times
Voted 5
Answered 1 times

Search




Leave an answer