开发者

ServerSocket accept behavior

I have the following snippet of code :

if (servsock == null) {
    System.out.println("HELLO1!");
    servsock = new ServerSocket(63456, 10);
    System.out.println("HELLO2!");
}
try {
    System.out.println("HELLO3!");
    sock = servsock.accept();
} catch (Exception ex) {
    if (servsock != null && !servsock.isClosed()) {
        System.out.println("PICO1!");
        servsock.close();
    }
    if (servsock != null && servsock.isClosed()) {
        System.out.println("PICO2!");
        manager.log("SERVER SOCKET closed and nulled.");
        servsock = null;
 开发者_开发百科   }
    sock = servsock.accept();
}
System.out.println("HELLO4!");
is = sock.getInputStream();
System.out.println("HELLO5!");
bis = new BufferedInputStream(is);
System.out.println("HELLO6!");

This code is run in a runnable's run() method, and when the file has been transferred, it is supposed to stop every communication.

The curious thing is, that it is not a loop. The code does accept, does makes a file transfer, but I don't understand why the HELLO1 is again on my screen. Thus, the second time I try to run again this code, gives me "Connection refused".

The "10" was a hack from me, but the original code, never uses backlog also.

Any suggestion please ?

The code running executing the previous is that :

final IClientInterface clientInterface = client.getClient();
final prgHolder = new ProgHolder();
Pong ftppong = new Pong();
ftppong.setFileNames(bout64.toByteArray());
ftppong.setDstFolder(dstFolder);
prgHolder.setName("pong");
prgHolder.setTask(pong);
Thread t = new Thread(new Runnable() {
    public void run() {
        try {
            IClientInterface.execute(prgHolder);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
});
t.start();

The exact problem now is, that when I reach the new ServerSocket(63456) command, the client gets a "Connection Refused", but the program in the distant PC, is wide open and wide listener! "netstat" confirms that!

So I rerun (second time) the program from an alternate window, passes all HELLO messages and completes the job!

Then the Thread stops in the distant PC, and unbinds the port 63456!

Why does it fail as code, but accepts incoming requests?


Based on this code you should see HELLO1 only once. However it is highly likely the caller of this code is in a loop otherwise there would be no point checking the previous value of servsock.

What is this going to do?

servsock = null;
}
sock = servsock.accept();

When you get an exception don't continue as if it didn't happen.

If you want to understand what your code is doing I suggest you use a debugger to step through your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜