Java后台创建Socket服务接收硬件终端发送的数据
最近项目中有遇到后台接收硬件终端发送的数据并解析存储的需求,代码总结如下(有时间再来一一讲解,最近比较忙):
@Override public void start() { ExecutorService pool = Executors.newCachedThreadPool(); try { if (enable) { return; } enable = true; serverSocket=new ServerSocket(port); Socket socket = null; BufferedInputStream reader = null; BufferedOutputStream writer = null; while (enable) { try { socket=serverSocket.accept();//阻塞方法 socket.setSoTimeout(100000); // start byte example reader = new BufferedInputStream(socket.getInputStream()); writer = new BufferedOutputStream(socket.getOutputStream()); int totalChar = 84; byte[] body = new byte[totalChar]; int len = reader.read(body, 0, 84); if (len < totalChar) { logger.error("收到包ERROR: " + new String(body, "UTF-8") + " 长度: " + len); logger.info("收到包ERROR: " + ByteUtil.bytesToBit(body)); logger.info(ByteUtil.parseByte2HexStr(body)); if (null != socket && !socket.isClosed()) { socket.close(); } continue; } else { logger.info("收到包: " + new String(body, "UTF-8")); logger.info(ByteUtil.bytesToBit(body)); logger.info(ByteUtil.parseByte2HexStr(body)); } T409_car_collects dbcollect = new T409_car_collects(); //硬件数据存储在这个对象中 byte[] idBytes = new byte[17]; System.arraycopy(body, 0, idBytes, 0, 17); String id = new String(idBytes); dbcollect.setTerminalid(id); //TODO } catch (Exception e) { logger.error("Parse socket error. ", e); if (null != socket && !socket.isClosed()) { socket.close(); } } } } catch (IOException e) { logger.error("", e); } finally { pool.shutdown(); } } @Override public void stop() { enable = false; if (null != serverSocket && !serverSocket.isClosed()) { try { serverSocket.close(); } catch (IOException e) { logger.error("close serverSocket err.", e); } } } class Handler implements Runnable { private T409_car_collects collect; private Socket socket; Handler(T409_car_collects collect, Socket socket) { this.collect = collect; this.socket = socket; } @Override public void run() { // TODO System.out.println("serv handler: "+collect.getRemark()); logger.error(MessageFormat.format("Terminalid {0} is not exist.", collect.getTerminalid())); T410_car_collects_log collect_log = new T410_car_collects_log(); BeanUtils.copyProperties(collect,collect_log); BeanUtils.copyProperties(collect_log,collect); t410_car_collects_logMapper.insertSelective(collect_log); List<T409_car_collects> ext = carownerService.getcar_runningdatabyterminalid(collect.getTerminalid()); if(ext ==null ){ t409_car_collectsMapper.insertSelective(collect); }else{ collect.setId(ext.get(0).getId()); Date now = new Date(); collect.setUpdatetime(now); t409_car_collectsMapper.updateByPrimaryKeySelective(collect); } try { PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"),true); pw.println("back to client."); pw.flush(); } catch (Exception e) { logger.error("send back socket client err.", e); } finally { try { socket.close(); } catch (IOException e) { logger.error("close socket err.", e); } } } }