socketclient的簡單封裝

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClientUtils {
	private static Logger  logger = LoggerFactory.getLogger(SocketClientUtils.class);  
	private static Socket socket;
	
	/**socket提交訪問數據
	 * @param url
	 * @param params
	 * @return
	 */
	public static String sendSocket(String url,int port,String sendMsg) throws Exception{
		logger.info("socket request url :"+url+"\nport:"+port+"\nsendMsg:"+sendMsg);
		OutputStream out = null ;
		InputStream in = null;
		String msg = null;
		try {
			if(null==socket||socket.isClosed()){
		    	socket = new Socket(url, port);  //啓動socket,並連接本地主機的相應端口號 
		    	socket.setKeepAlive(true);
		    }
			out = socket.getOutputStream();//獲取服務端的輸出流,爲了向服務端輸出數據  
		    in=socket.getInputStream();//獲取服務端的輸入流,爲了獲取服務端輸入的數據  
		    out.write(sendMsg.getBytes("GBK"));//發送數據給服務端  
		    out.flush();
		    byte[] buff = new byte[256];
		    int len = 0;
		    len =  in.read(buff);
		    msg =new String(buff,0,len,"GBK");
		} catch (Exception e) {
			if(null!=in){
				in.close();
			}
			if(null!=out){
				out.close();
			}
			if(null!=socket){
				socket.close();
			}
			out = null;
			in = null;
			socket = null;
			e.printStackTrace();
			logger.error("socket異常:"+e.getMessage());
			throw new Exception(e.getMessage());
		}finally{
			if(null!=in){
				in.close();
			}
			if(null!=out){
				 out.close();
			}
		    if(socket.isInputShutdown()){
		    	socket.shutdownInput();
		    }
		    if(socket.isOutputShutdown()){
		    	socket.shutdownOutput();
		    }
		    logger.info("socket response msg :"+msg);
		}
	    return msg;
	}
	
}

 

發佈了41 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章