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;

扫描二维码关注公众号,回复: 854530 查看本文章

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();

}

}

}

}

猜你喜欢

转载自lx0088.iteye.com/blog/2198705
今日推荐