tags:

views:

46

answers:

2
+1  Q: 

java Sockets issue

Hello all

Im making a listener which basically listens on a port for like forever and as soon as a client connects it then initiates a transfer in a manner such that the listener first sends out a string "@AUTH@" and then the clien responds and so on.

My code segment for the above is as follows

while(true){


try {


    Socket incoming=connection.accept();
    while(!incoming.isClosed())
    { 
        out = new PrintWriter(incoming.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
        BufferedInputStream is = new BufferedInputStream(incoming.getInputStream());    //inputstream to get data from the socket
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        out.println("@AUTH@");
}
}
catch(Exception e){}
}

where 'connection' is an object of class ServerSocket. Now when im testing my code using the hyoperterminal, im like connecting to the port and on the first connection, the string "@AUTH@" is displayed but then once i disconnect from that port using Hyperterminal and connect again, the string "@AUTH@" is not displayed. I basically want this string to be displayed every time a client connects to that port as it acts as the initiation for the whole authorization process.

Any pointers would be of great help.

CHeers

+1  A: 

I suspect that the problem is that you're not reading any data. If hyperterminal has sent anything (e.g. telnet negotiation codes) then there's still data for you to read from the socket, so it probably isn't treating it as being closed. Therefore your code is still dealing with the first connection, and won't get round to accepting the new one.

Aside from dealing with each connection more appropriately, you may wish to spawn a new thread for each connection - currently while one connection is "busy" you won't be able to connect again, as you've already seen.

You should be able to verify all of this using logging... logging which should also show if there have been any exceptions: catching Exception and swallowing it is going to make your life much harder in terms of working out what's going on.

Jon Skeet
A: 

Your code doesn't make any sense.

(a) Socket.isClosed() returns true when you close the socket and at no other time. (b) You are creating new input and output streams every time around this loop. They should be created once.

EJP