• Apache下的SocketClient的使用


    最近公司对接一个socket的接口,由于不需要做服务端口监听,自己手写socket当然也不复杂,但也需要重新实现对数据的读写操作,为了高效的完成任务。想到了apach下的网络包
    里面就有一个socketClient抽象类,我就拿来使用了,

    直接拿来时候用 不用多说直接上代码了

    public class ShortSocketClientConnetion extends DiscardTCPClient {
        protected  final static Logger logger = LoggerFactory.getLogger(EsbClientSerivceTest.class);
    
        public ShortSocketClientConnetion(String ip,int port) throws IOException {
            this();
            this._hostname_ = ip;
            this._defaultPort_ = port;
            this.connect(ip,port);
        }
        public ShortSocketClientConnetion(EsbInterfaceConfig config) throws IOException {
            this();
            this._hostname_ = config.getIp();
            this._defaultPort_ = config.getPort();
            this.setDefaultTimeout(config.getConnectTimeout());
            this.setConnectTimeout(config.getConnectTimeout());
            this.connect(config.getIp(),config.getPort());
            this.setSoTimeout(config.getReadtimeout());
        }
        public ShortSocketClientConnetion(){
            super();
        }
    
        public InputStream getInputStream() {
            return this._input_;
        }
    
        public String sendMessage(String msg) throws IOException {
            logger.info("S:{}",msg);
            String strLen ="0000" + msg.getBytes().length;
            StringBuffer bf = new StringBuffer();
            bf.append(strLen.substring(strLen.length()-6));
            bf.append(msg);
            System.out.println(bf.toString());
            this.getOutputStream().write(bf.toString().getBytes());
            byte[] bytes = this.readStream(this.getInputStream());
            String ret = new String(bytes, getCharset());
            logger.info("R:{}",ret);
            return ret;
        }
    
        public byte[] readStream(InputStream inStream) throws IOException {
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            return outSteam.toByteArray();
        }
    }
    
    

    读写操作是通过

       //发送数据
      this.getOutputStream().write(bf.toString().getBytes());
       //读取数据
      this.getInputStream().read(buffer) 
    
  • 相关阅读:
    [LeetCode] Contains Duplicate II
    [LeetCode] House Robber II
    [LeetCode] Permutations II
    [LeetCode] Permutations
    [LeetCode] Next Permutation
    谈谈套接字
    基于Linux系统的Nagios网络管理模块的实现
    Windows/Linux下磁盘使用的图形化工具简介
    利用日志使管理Linux更轻松
    实际感受美丽的Linux(多组视频)
  • 原文地址:https://www.cnblogs.com/lameclimber/p/12307941.html
Copyright © 2020-2023  润新知