socket短連接客戶端Java實現

public class SocketClient {
	
	private static Log logger = LogFactory.getLog(SocketClient.class);
	private static Socket socket; //socket連接
	private static boolean connection = false;//socket是否連接
	private static int connectcount = 0;
	
	
	/**
	 * 打開socket
	 * @param data  能耗數據xml
	 * @return 是否成功 0-成功
	 * @throws IOException 
	 * @throws DocumentException 
	 */
	public static String csocket(String sendData, int type) throws IOException, DocumentException {
		open();
		if(connection==false) {			
			return null;
		}
		
		// 處理髮送的報文 轉換成byte[]
 		byte[] message = getTcpMessage(sendData, type);
	    // 發送報文並獲取返回報文
 		Document receiveData = sendAndRecMsg(message);
 		
		return XmlService.formatXML(receiveData,"utf-8");
	}

	/**
	 * 發送數據
	 * @param message 報文
	 * @return 服務器回覆 style
	 */
	public static byte[] sendAndRecMsg(byte[] message){
		
		if (message == null) {
			return null;
		}
		
		Document document = null;
		try{
			InputStream in = socket.getInputStream();  //獲取輸入流,並創建相應的數據輸入流
			OutputStream out = socket.getOutputStream();//獲取輸出流,並創建相應的數據輸出流
			
			out.write(message);
			out.flush();
			
			int count = 0;
			int k = 0;
			while( count ==0 && k<100 ){
				count = in.available();
				k++;
				Thread.sleep(200);
			}
			byte[] receive = new byte[count];
			int readCount = 0; // 已經成功讀取的字節的個數
			while (readCount < count) {
				readCount += in.read(receive, readCount, count - readCount);
			}
			
			if(receive.length == 0){
				return null;
			}
		 		
						
		
			 
		} catch (Exception e) {
			logger.error(e+"  發送異常,重新認證發送數據!");
			e.printStackTrace();
		}
		return receive;
	}
	
	/**
	 * 打開socket連接
	 */
	public static boolean open(){
		while(connectcount<60 && !connection){
			try{
				socket = new Socket(); //重新連接需要new Socket,否則報錯
				String ipAddr = GetSysConfService.tcp_ip;
				int port =GetSysConfService.tcp_port;
				
				//ipAddr="172.18.3.31";
				
				socket.connect(new InetSocketAddress(ipAddr, port),0);
				connection = true;
				connectcount = 0;
				Thread.sleep(1000);//創建連接休眠1s,若不sleep等待,將無法接受到認證信息
			}catch(Exception ex){
				connectcount++;
				logger.error("與服務器建立socket連接第"+connectcount+"次失敗",ex);
				try {
					if(connectcount<=30) Thread.sleep(10000);
					else if(connectcount<20) Thread.sleep(30000);
					else if(connectcount<30) Thread.sleep(60000);
					socket.close();//建立失敗,以防萬一,close
				} catch (InterruptedException e) {
					logger.error(e);
					e.printStackTrace();
				} catch (IOException e) {}
			}
		}
		return connection;
	}
		
	/**
	 * 關閉socket
	 */
	public void close(){
		if(connection){
			try {
				socket.close();
			} catch (IOException e) {
				logger.error(e);
				e.printStackTrace();
			}
			connection = false;
		}
		
	  }
	
	
	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章