开发者

Reconnect to server when socket is closed

I've got a program that opens N sockets to a server, each one in a different thread. After sending two string for login porpuse, the program listen to the server, until an error occurs and the server sends the disconnect command, and the socket is closed. I want the program to reconnect once the server closes the socket : is it possible?

            SocketList.add(new ConnectionHandler(id, actualSocket, out, in));

            SocketRead p = new S开发者_如何学CocketRead(in, out, rowid);
            new Thread(p).start();

I'd like that, when the socketread object receive the "DISCONNECT" command, the socket is restarts ( if needed, opening another thread).


I'm not sure what SocketList, ConnectionHandler or SocketRead are, so I'll assume they are classes that you've written for your application.

If you want to be able to reconnect, then you are going to have to change the structure of your code. On the one hand, the SocketRead object doesn't have the information needed to allow it to reconnect. On the other hand, the controlling code (your snippet) isn't able to detect the disconnect command.

It is not clear what will work best, but here are a couple of options:

  • pass the Socket (or the InetAddress and port number) to SocketRead and make it responsible for opening a new socket.

  • pass the Thread to the ConnectionHandler and make it responsible for detecting the death of the thread, creation of a new Socket and creating a new Thread.

  • pass the ConnectionHandler to the SocketRead object, hand have the latter call a callback or event handler method in the former when the socket disconnect occurs.


In the event handler of the DISCONNECT event, put in your reconnection logic. For more information on how to write EventHandlers refer this link.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜