日期:2014-05-19 浏览次数:20810 次
@Override public void run() { while (!bExit ) { try { System.out.println("kaishile"); send(); System.out.println("开始了,开始了"); Thread.sleep(15000); } catch( InterruptedException e) { e.printStackTrace(); } } }
private void send() { try { if( client == null || client.isClosed()) { client = new Socket(InetAddress.getByName(mServerAddr),mServerPort); client.setSoTimeout(60000); client.setTcpNoDelay(true); outP = client.getOutputStream(); inP = client.getInputStream(); _log.debug("new socket is created, device id is " + mDeviceID); } } catch (IOException e) { System.out.println("报错了IOException"); e.printStackTrace(); _log.error("deviceID:" + mDeviceID + " IOException "); try { outP.close(); inP.close(); client.close(); client = null; } catch (IOException e1) { e1.printStackTrace(); } }
class TestClient1 implements Runnable{ Socket client = null; InetSocketAddress serverAddress = null; boolean bExit = false; public TestClient1(){ this("127.0.0.1", 7777); } public TestClient1(String serverIp, int port){ this.serverAddress = new InetSocketAddress(serverIp,port); } @Override public void run() { for(int i=0;!bExit;i++){ if(connect2Server()){ //连接成功 }else{ System.out.println("连接失败,重试("+i+")..."); try { Thread.sleep(1000*15); } catch (InterruptedException e) { } } } } boolean connect2Server(){ boolean done = false; try{ client = new Socket(); client.connect(serverAddress, 1000*60); client.setSoTimeout(60*1000); done = client.isInputShutdown() & client.isOutputShutdown(); }catch(Exception ex){ System.err.println("报错了:"+ex.getMessage()); try{ if(null!=client) client.close(); }catch(Exception ex1){ } done = false; } return done; } }