zoukankan      html  css  js  c++  java
  • 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) 
    
  • 相关阅读:
    Linux命令-网络命令:netstat
    Linux命令-网络命令:traceroute
    Linux命令-网络命令:lastlog
    Linux命令-网络命令:last
    mongodb3.4 安装及用户名密码设置
    MySQL表名不区分大小写的设置方法
    数据库设计中的四个范式
    dubbo本地调试直连
    com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1169 > 1024)
    Linux服务器时间同步
  • 原文地址:https://www.cnblogs.com/lameclimber/p/12307941.html
Copyright © 2011-2022 走看看