qq_34181339
qq_34181339
2019-12-12 17:53
采纳率: 57.1%
浏览 389
已采纳

重金求解,为什么我接收不到socket服务端返回的信息,代码如下,这个logger.debug("result:"result)为什么总是空,确认了服务端的确返回到了socket,怎样才能正确从socket取到值呢?

这是socket客户端代码

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client extends Thread {
    Socket socket = null;
    public String result = "";
    public String in = "";
    public Client(String host, int port, String in) {
        try {
            in = new String(in.getBytes(),"GBK");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.in = in;
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(1000);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

//    public void shutDown() throws IOException {
//        if (socket != null) {
//            synchronized (socket) {
//                socket.close();
//            }
//        }
//        System.out.println("StopClose.shutDown() complete");
//    }

    @Override
    public void run() {
        new sendMessThread().start();
        super.run();
        try {
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class sendMessThread extends Thread{
        @Override
        public void run() {
            super.run();
            Scanner scanner=null;
            OutputStream os= null;
            try {
                scanner=new Scanner(System.in);
                os= socket.getOutputStream();
//                String in;
//                do {
//                  in=scanner.next();
//                    os.write((""+in).getBytes());
//                    os.flush();
//                } while (!in.equals("bye"));
                for(int i =0;i<1;i++) {
                    os.write((""+in).getBytes());
                    os.flush(); 
                }

                BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
                String str = "";
                System.out.println("RESULT AS FOLLOWING:");
                while ((str = rd.readLine()) != null) {
                  System.out.println(str);
                }
//                str = rd.readLine();
                Client.this.result = str;
                System.out.println("Client.this.result:"+Client.this.result);
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            scanner.close();
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
    }
    public static void main(String[] args) {
//      Client clientTest=new Client("88.6.13.66", 13000);
//      Client clientTest=new Client("127.0.0.1", 1234,"");
//      clientTest.start();
    }
}

这是调用的代码

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.Types;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

public class FaceCheckManage {
    private final static String DB_ALIAS = "ALIAS";//数据源

    private static final String TRXZONE = "trxZone";//输入|地区号
    private static final String TYPE = "type";//输入|操作类型 add-注册 check-识别 del-删除
    private static final String IMG = "img";//输入|人脸数据
    private static final String ID = "id";//输入|编号
    private static final String VALUE = "VALUE";//输出|转发数据

    public String process(IWFEngine engine, WFActivity activity, WFData wfd, String wfName)
            throws ParamNotExistException, com.zjft.bpe.stdlib.exception.UnrecognizedScopeException {
        BizDataModule dm = wfd.getDataModule();
        ZjLogger logger = LoggerUtil.getLog(dm.getChannelId(), dm.getTxCode());
        ModuleUtil moduleUtil = new ModuleUtil(wfd, wfd.getDataModule(), activity, logger);

        String trxZone = moduleUtil.getParamValue(TRXZONE);
        logger.debug("trxZone:"+trxZone);
        String type = moduleUtil.getParamValue(TYPE);
        String imgBase64 = moduleUtil.getParamValue(IMG);
        String id = moduleUtil.getParamValue(ID);

        Connection conn = wfd.getTxConnection(moduleUtil.getParamValue(DB_ALIAS));

        try {
            /*是否已注册*/
            boolean registedFlag = isRegisted(id, conn, logger);
            if("add".equals(type)&&registedFlag==true) {
                CommonUtil.setResponseMsg("FFFFF", "用户已注册,请先删除人脸数据", moduleUtil);
                return "fail";
            }else if(("check".equals(type)||"del".equals(type))&&registedFlag==false) {
                CommonUtil.setResponseMsg("FFFFF", "用户人脸数据未注册", moduleUtil);
                return "fail";
            }
        } catch (Exception e) {
            logger.error("查询是否已注册发生异常",e);
            CommonUtil.setResponseMsg("FFFFF", "查询是否已注册发生异常", moduleUtil);
            return "fail";
        }

        JSONObject sysParams = null;//系统参数列表
        try { 

            //获取人脸识别配置参数
            sysParams = getSysParam(type,conn, logger);
        }catch (TradeException e) {
            CommonUtil.setResponseMsg("FFFFF", e.getMessage(), moduleUtil);
            return "fail";
        } catch (Exception e) {
            logger.error("查询人脸识别系统参数发生异常",e);
            CommonUtil.setResponseMsg("FFFFF", "查询人脸识别系统参数发生异常", moduleUtil);
            return "fail";
        }

        String ip = sysParams.getString("ip");
        String url =sysParams.getString("url");

        //组参数
        JSONObject paramMap = new JSONObject();
        if("add".equals(type)) {
            paramMap.put("trxZone", trxZone);
            paramMap.put("programName", "e");
            paramMap.put("id", id);
            paramMap.put("img1", imgBase64);
            paramMap.put("imgFace1", "50,60,100,120");
            paramMap.put("hack1", 1);
            paramMap.put("customerAgreement", 1);

            String trxString = "10032";
            String jsonString = paramMap.toJSONString();
            int length = jsonString.length()+10;
            String lenString = getLenString(length);
            String totalString = trxString+lenString+jsonString;
            logger.debug("totalString:"+totalString);

            Client client = new Client("88.6.13.66", 13000,totalString);
            client.start();
            String result = client.result;
            logger.debug("result:"+result); 
            result = result.substring(5,result.length());
            moduleUtil.setParamValue(VALUE, result);
            logger.debug("VALUE:"+result);
            JSONObject resultJsonObject = JSONObject.parseObject(result);
            logger.debug("resultJsonObject:"+resultJsonObject);


            //新增参数

        }else if("check".equals(type)) {
            paramMap.put("trxZone", trxZone);
            paramMap.put("programName", "e");
            paramMap.put("id", id);
            paramMap.put("img1", imgBase64);
            paramMap.put("imgFace1", "50,60,100,120");
            paramMap.put("threshold", 0.001);
            paramMap.put("hack1", 1);

            String trxString = "10034";
            String jsonString = paramMap.toJSONString();
            int length = jsonString.length()+10;
            String lenString = getLenString(length);
            String totalString = trxString+lenString+jsonString;
            logger.debug("totalString:"+totalString);

            Client client = new Client("88.6.13.66", 13000,totalString);
            client.start();
            String result = client.result;
            logger.debug("result:"+result);


            result = result.substring(5,result.length());
            moduleUtil.setParamValue(VALUE, result);
            logger.debug("VALUE:"+result);
            JSONObject resultJsonObject = JSONObject.parseObject(result);
            logger.debug("resultJsonObject:"+resultJsonObject);

        }else if("del".equals(type)){
            paramMap.put("trxZone", trxZone);
            paramMap.put("programName", "e");
            paramMap.put("id", id);

            String trxString = "10035";
            String jsonString = paramMap.toJSONString();
            int length = jsonString.length()+10;
            String lenString = getLenString(length);
            String totalString = trxString+lenString+jsonString;
            logger.debug("totalString:"+totalString);
            try {
                totalString = new String(totalString.getBytes(),"GBK");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Client client = new Client("88.6.13.66", 13000,totalString);
            client.start();
            String result = client.result;
            logger.debug("result:"+result);

            result = result.substring(5,result.length());
            moduleUtil.setParamValue(VALUE, result);
            logger.debug("VALUE:"+result);
            JSONObject resultJsonObject = JSONObject.parseObject(result);
            logger.debug("resultJsonObject:"+resultJsonObject);

        }else {
            CommonUtil.setResponseMsg("FFFFF", "错误的操作类型", moduleUtil);
            return "fail";
        }
        String param = paramMap.toJSONString();
        try {
            param = "params="+URLEncoder.encode(param,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("转换为请求数据失败");
            return "fail";
        }


        return "ok";
    }

    /**
     * <p> 函数名:isRegisted </p> 
     * <p> 函数功能:查询该编号用户人脸信息是否已注册  </p> 
     * <p> 处理过程:(描述这个方法的处理逻辑)</p> 
     * <p> 输入参数描述: </p> 
     * <p> 输出参数描述: </p> 
     * <p> 异常处理描述: </p> 
     * <p> 创建信息:liuyuan/2019年6月4日 下午3:29:48/versoin</p> 
     * <p> 修改信息:(修改人名、修改人名.../最后修改时间/修改版本号)</p> 
     * <p> 多个版本修改,则每次新增一行修改信息</p>
     * @throws Exception 
     */
    private boolean isRegisted(String id,Connection conn,ZjLogger logger) throws Exception {
        String sql = "select t.id from USER_FACE_RECORD t where t.id_number=? or t.user_no=?";
        List<SQLPara> sqlParas = new ArrayList<>();
        sqlParas.add(new SQLPara("id_number", Types.VARCHAR, id));
        sqlParas.add(new SQLPara("user_no", Types.VARCHAR, id));
        CachedRowSet rlt = DbOperate.executeQueryByParamName(sql, sqlParas, conn, logger);
        return rlt.next();
    }

    /**
     *
     * <p>Title: getSysParam</p>
     * <p>Description: 查询人脸识别相关参数 </p>
     * @param type
     * @param conn
     * @param logger
     * @return
     * @throws TradeException
     * @throws Exception
     */
    private JSONObject getSysParam(String type,Connection conn, ZjLogger logger) throws TradeException,Exception {
        JSONObject sysParam = new JSONObject();

        String qrySysParamSQL = " select t.param_value from SYS_PARAM t where t.param_name=? ";
        List<SQLPara> sqlParas = new ArrayList<>();

        // 查询ip
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_ip"));
        CachedRowSet ipRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!ipRlt.next()) {
            throw new TradeException("请先配置人脸识别服务器地址(faceCheck_ip)");
        }
        sysParam.put("ip",ipRlt.getString("param_value"));
        sqlParas.clear();

        // 查询url
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_url"));
        CachedRowSet urlRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!urlRlt.next()) {
            throw new TradeException("请先配置人脸识别转发url(faceCheck_url)");
        }
        sysParam.put("url",urlRlt.getString("param_value"));
        sqlParas.clear();

        // 查询baseFlag
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_baseFlag"));
        CachedRowSet baseFlagRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!baseFlagRlt.next()) {
            throw new TradeException("请先配置人脸识基准照标示(faceCheck_baseFlag)");
        }
        sysParam.put("baseFlag",baseFlagRlt.getInt("param_value"));
        sqlParas.clear();

        // 查询threshold
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_threshold"));
        CachedRowSet thresholdRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!thresholdRlt.next()) {
            throw new TradeException("请先配置人脸识误识率阈值(faceCheck_threshold)");
        }
        sysParam.put("threshold",thresholdRlt.getString("param_value"));
        sqlParas.clear();

        //查询channel
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_channel"));
        CachedRowSet channelRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!channelRlt.next()) {
            throw new TradeException("请先配置人脸识别转发业务渠道编号(faceCheck_channel)");
        }
        sysParam.put("channel",channelRlt.getString("param_value"));
        sqlParas.clear();

        //交易编号写死,加操作类型大写进行区分
        sysParam.put("trCode","SXFH-BF-SWXJ-ITMS-FACE-"+type.toUpperCase());

        //查询appName
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_appName"));
        CachedRowSet appNameRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!appNameRlt.next()) {
            throw new TradeException("请先配置人脸识别应用名(faceCheck_appName)");
        }
        sysParam.put("appName",appNameRlt.getString("param_value"));
        sqlParas.clear();

        //查询appInfo
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_appInfo"));
        CachedRowSet appInfoRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!appInfoRlt.next()) {
            throw new TradeException("请先配置人脸识别客户端APP信息(faceCheck_appInfo)");
        }
        sysParam.put("appInfo",appInfoRlt.getString("param_value"));
        sqlParas.clear();

        //查询retentionTime
        sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_retentionTime"));
        CachedRowSet retentionTimeRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger);
        if (!retentionTimeRlt.next()) {
            throw new TradeException("请先配置人脸识清理时间(faceCheck_retentionTime)");
        }
        sysParam.put("retentionTime",retentionTimeRlt.getString("param_value"));
        sqlParas.clear();

        logger.debug("sysParam:"+sysParam);
        return sysParam;
    }

    public String getLenString (int length) {
        NumberFormat  formatter = NumberFormat.getNumberInstance();   
        formatter.setMinimumIntegerDigits(5);   
        formatter.setGroupingUsed(false);   
        String lenString = formatter.format(length);   
        return lenString;
    }

}

这个地方为什么总是空的
图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • caozhy
    已采纳

    client.start();是异步调用的,要等它执行完毕返回result。你的代码直接接下来调用client.result此时尚未返回

    点赞 评论