java socket 重新连接

 

 import java.io.IOException;

import java.net.InetAddress;

import java.net.Socket;

import java.net.UnknownHostException;

 

public class MySocketConnection {

 

public static Socket socket ;

public InetAddress ia;

 

public static Socket getSocket(){

try {

if(socket == null){

return new Socket(InetAddress.getByName("192.168.0.113"),12345);

}else{

return socket;

}

} catch (UnknownHostException e) {

 

} catch (IOException e) {

 

}

return null;

}

 

}

 

public class Client {

 

public void sendMsg(int i){

try{

System.out.println("发送第"+i+"次");

MySocketConnection.getSocket().getOutputStream().write(("发送第"+i+"次").getBytes("gbk"));

}catch(Exception e){

MySocketConnection.socket = null;

sendMsg(i);

}

}

 

}

 

public class Main {

 

/**

* @param args

* @throws UnknownHostException 

* @throws IOException 

* @throws UnsupportedEncodingException 

*/

public static void main(String[] args) throws UnknownHostException  {

 

   Client c = new Client();

 

int i = 0;

 

while(true){

i ++ ;

c.sendMsg(i);

try {

Thread.sleep(10000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

 

}

 

}

你可能感兴趣的:(技术博客,socket,自动重新连接,自动重连)