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;
	}
	
}

 

你可能感兴趣的:(日常积累)