java - Singleton networking object gives error on second call -
communication class of singleton object created:
import java.net.*; import java.io.*; import java.util.scanner; public class communication { private static communication minstance = null; private static final string request_login = "login"; private bufferedoutputstream socketoutput = null; private printwriter printout = null; private socket socket = null; private scanner reader = null; private communication() { //connect server using loopback address try{ socket = new socket("127.0.0.1", 4242); //set inputs , out puts socketoutput = new bufferedoutputstream(socket.getoutputstream()); printout = new printwriter(socket.getoutputstream(), true); reader = new scanner(socket.getinputstream()); } catch( unknownhostexception uhe){ uhe.printstacktrace(); } catch( ioexception ex){ ex.printstacktrace(); } } public static communication getinstance(){ if(minstance == null) { minstance = new communication(); } return minstance; } //sample method requesting login public boolean login(string u, string p){ try{ string username = u; string password = p; printout.printf("%s!%s@%s\n", request_login, username, password); int loginstatus = reader.nextint(); if (loginstatus == 1){ socketoutput.close(); socket.close(); return true;} else{ socketoutput.close(); socket.close(); return false; } } catch( ioexception ex){ ex.printstacktrace(); return false; } } }
another class using singleton object repeatedly:
public class go{ public static void main(string[] args) { communication.getinstance().login("user", "password"); communication.getinstance().login("user", "password"); } }
first call alright , authentication happens. second call invokes error:
exception in thread "main" java.util.nosuchelementexception @ java.util.scanner.throwfor(scanner.java:907) @ java.util.scanner.next(scanner.java:1530) @ java.util.scanner.nextint(scanner.java:2160) @ java.util.scanner.nextint(scanner.java:2119) @ communication.login(communication.java:49) @ go.main(go.java:7)
how can use object repeatedly ?
the login method closes socket, on second call scanner works on dead input stream. in application flow broken.
the communicator singleton, , break because invalidate it's assets in login method. getinstance() method finds singleton still set (because not set singleton null @ end of login) , returns dead object.
then scanner tries readint on closed socket's input stream. suppose not supposed work.
Comments
Post a Comment