开发者

How to reconnect a socket when catch a SocketException in java?

开发者 https://www.devze.com 2023-04-13 01:22 出处:网络
I\'ve met a problem that when I process my data on my program, that the server may g开发者_如何学JAVAetoff its socket of my client program, but i need to catch this exception and reconnect it to run m

I've met a problem that when I process my data on my program, that the server may g开发者_如何学JAVAetoff its socket of my client program, but i need to catch this exception and reconnect it to run my program. i did not use the serverSocket but all use the Socket to create an object. I need your help. the implement code in detail is welcome. thanks


You can't. You have to create a new one if you're the client, and just hope the client will do that if you're the server.


try to create new one with same ip and port

while (!socket.isConnected()) {
                    try {
                        socket = new Socket(inetAddress,  port);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
0

精彩评论

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