Continuously read objects from an ObjectInputStream in Java

[亡魂溺海] 提交于 2019-11-28 14:33:03

try using this

Server side
1.Server running on a separate thread

public class ServeurPresence implements Runnable {

public final static int PORT = 20000 ;
public final static String HOSTNAME = "localhost" ;
public static enum Action {CONNEXION, MSG, DECONNEXION,USER, FINCLASSEMENT};

ServerSocket serveur ;
static List<String> names ;

 */
public ServeurPresence() 
{

    System.out.println("Start Server...");
    try 
    {
        serveur = new ServerSocket(PORT) ;
        new Thread(this).start();
        //javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {   createAndShowGUI();}    }   );
    } 
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
/**
 * @param args
 */
public static void main(String[] args)
{
    new ServeurPresence();

}
@Override
public void run() 
{
    System.out.println("server runs");

        while(true)
        {
            try {

                Socket sock = serveur.accept();
                ServiceClientsThread thread= new ServiceClientsThread(sock);
                thread.start();

            }
            catch (IOException e) 
            {
                System.out.println("Error with  socket");
                e.printStackTrace();        
            }
        }

}

}


2. A Thread to handle each Client:ServiceClientThread

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;


 public class ServiceClientsThread extends Thread{
    private Socket sock ;
ServiceClientsThread(Socket sock)
{
        //super();
        this.sock=sock;
}

@Override
public void run() 
{
    DataInputStream is ;
    DataOutputStream os ;
    String name =null ;

    try {

        is = new DataInputStream(sock.getInputStream()) ;
        os = new DataOutputStream(sock.getOutputStream()) ;
        ServeurPresence.Action act ;

        do {
            // read Action              
            act = ServeurPresence.Action.valueOf(is.readUTF()) ; // read string -> enum
            System.out.println("action :"+act);
            switch (act) {

            case CONNEXION :
                name = is.readUTF(); //read client name
                System.out.println("Name :"+name);
                os.writeUTF("Hi");//send welcome msg
                break ;
            case MSG :
                String msg = is.readUTF();
                 os.writeUTF("OK");//response
                break ;
            case DECONNEXION :
                System.out.println(name+" is logged out");
                break ;
            }

        } while (act!=ServeurPresence.Action.DECONNEXION) ;

        // the end
        is.close();
        os.close();
        sock.close();

    } catch (IOException e) 
    {
        System.out.println("Error with "+name+" socket");
        e.printStackTrace();        
    }
}

}


3. Client side

    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;


public class Client {
/**
 * 
 */
Client(String name)
{
    System.out.println("Start Client...");

    try {

        Socket sock = new Socket(ServeurPresence.HOSTNAME,ServeurPresence.PORT) ;
        DataOutputStream os = new DataOutputStream(sock.getOutputStream()) ;
        DataInputStream is = new DataInputStream(sock.getInputStream()) ;

                    System.out.println("Send "+name+" to server");

        // CONNECTION : Action then value
        os.writeUTF(ServeurPresence.Action.CONNEXION.name()) ; // send action : write enum -> String
        os.writeUTF(name) ; // send the name

                    //read server welcome msg
        String msg = is.readUTF();
                    System.out.println("Welcome msg: "+msg);

        /*  Your actions here : see example below */
        try 
        {
            Thread.currentThread().sleep(4000);
            os.writeUTF(ServeurPresence.Action.MSG.name()) ; // send action : write enum -> String
            os.writeUTF("My message here") ; // send msg
            Thread.currentThread().sleep(4000);
            msg = is.readUTF();//server response message
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
        /************************************************/

        //CLOSE
        os.writeUTF(ServeurPresence.Action.DECONNEXION.name()) ; // send action
        System.out.println("Log out");
        os.close();
        sock.close();

    }
    catch (UnknownHostException e) 
    {
        System.out.println(ServeurPresence.HOSTNAME+ " unknown");
        e.printStackTrace();
    } 
    catch (IOException e)
    {
        System.out.println("Impossible to connect to "+ServeurPresence.HOSTNAME+ ":"+ServeurPresence.PORT);
        e.printStackTrace();
    } 
}

}


4. In your case use readObject()/writeObject() instead of readUTF()/writeUTF() to write your config objects

Try this and let me know how it goes:

while (1==1)
{
    StubConfig = (StubConfiguration)mObjectIn.readObject();
    Thread.sleep(100); //Saves CPU usage
}

EOFException is thrown by readObject() when the peer has closed the connection. There can never be more data afterwards. Ergo you can't have written multiple objects at all: you closed the connection instead.

Very late answer, but just for future reference. I have been having problems sending Objects via sockets because the method flush() is not working properly.

I solved this problem just by switching flush() to reset().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!