• 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) 
    
  • 相关阅读:
    洛谷 P4708
    NFLSOJ 1060
    Codeforces 1264D
    Solution -「多校联训」Sample
    Solution -「多校联训」光影交错
    Solution -「LOJ #138」「模板」类欧几里得算法
    Solution -「LOJ #141」回文子串 ||「模板」双向 PAM
    Codeforces Round #700 (Div. 2)
    Codeforces Round #698 (Div. 2) C and D
    「NOI 2021」题解
  • 原文地址:https://www.cnblogs.com/lameclimber/p/12307941.html
Copyright © 2020-2023  润新知