如何在多线程套接字连接中实现读写方法



我有一个从LIS机器读取和写入数据的程序。我正在从特定端口读取数据,并将数据写入数据库表。当我从表中读取数据并将它们添加到Arraylist中时,就是在添加重复的记录。我找不到解决办法。

代码如下:

public class PacsMultiThread extends Thread{
    private static Logger logger = Logger.getLogger(PacsMultiThread.class);
    // instance for Server socket and Socket class
    private ServerSocket serverSocket = null;
    private Socket socket = null;  
    ServerParams params = Configuration.getConfig().getServerParams();
    PacsMultiThread() {
        super("PacsMultiThread");
        try {
            // listen on local port
            serverSocket = new ServerSocket(Configuration.getConfig().getHostParams().getPort());
        } catch (IOException e) {
            logger.error("Could not listen on port: " + Configuration.getConfig().getServerParams().getPort() + ", " + e);
            System.exit(1);
        }
    }
    /*
     * thread run method call
     * @see java.lang.Thread#run()
     * Mohammod Hossain
     */
     public void run() {
         logger.info("run method is calling... ");
            if (serverSocket == null)
                return;
            while (true) {              
                try {
                    socket = serverSocket.accept();
                     logger.info("connection status: "+ socket.isConnected());
                } catch (IOException e) {
                    logger.error("Accept failed: " + Configuration.getConfig().getServerParams().getPort() + ", " + e);
                    System.exit(1);
                }           
                    try {
                        // readData();
                        //calling new Thread for reading data from port
                        ReadHandler readThread = new ReadHandler(socket);
                        readThread.start();
                       // writeData(socket);
                        //calling new Thread for writing  data into port
                        WriteHandler writeThread = new WriteHandler(socket);
                        writeThread.start();
                      } catch (Exception e) {
                          logger.error(e.getMessage());
                        }         
            }
        }


    public class WriteHandler extends Thread {
         private static Logger logger = Logger.getLogger(WriteHandler.class);
        private Socket socket;
    ServerParams params = Configuration.getConfig().getServerParams();
    OutputStream out = null;
    public WriteHandler(Socket socketConnection){
        super();
        this.socket = socketConnection;
    }
    @Override
    public void run() {
        writeData(socket);
    }
    private void writeData(Socket socket){
         /*
          * calling  writeData method for data write to port
          * @param Socket socket
          */
         logger.info("writeData method is called :: ");      
          try{ 
              //calling client socket method for connect to server port
             // logger.info(" client socket "+socket.getRemoteSocketAddress());  
              // check data exist in table in HL7001;
                List<HL7001> orderList = new ArrayList<HL7001>();
                PacsDao pacsDao = new PacsDao();
                orderList = pacsDao.getAllOrder();              
                //PrintWriter pw = new PrintWriter(theOutput, false);   
                int msgCount = 0;
                if(orderList.size() > 0){   
                    for(int i = 0;i<orderList.size();i++){
                    logger.info("orderList.size(): " + orderList.size());
                    HL7001 model = orderList.get(i);
                    logger.info("message from HL7001 Table :: " +"Msg Order No: "+
                            model.getOrderNo() +"n"+" msg no:"+ model.getHl7MsgNo()+"n"+" message: "+model.getHl7Msg());

                    //for(HL7001 model:orderList){                  
                    String tableMessage = model.getHl7Msg();
                    // read ADT Message from Table HL7001;
                    //readADTMsg(tableMessage);
                    // logging TABLE MESSAGE  data into file

                        StringBuffer transmitMsg =  new StringBuffer();
                        transmitMsg
                        .append(START_OF_BLOCK)
                        .append(tableMessage)
                        .append(END_OF_BLOCK)
                        .append(CARRAIGE_RETURN);
                        // write data to port
                         socket = new Socket(Configuration.getConfig().getServerParams().getUrl(), Configuration.getConfig().getServerParams().getPort());
                         if(socket.isConnected()){ 
                             logger.info(socket.getRemoteSocketAddress()+" port is connected ");
                             HL7007 hl7007 = new HL7007();
                             hl7007.setMsgNo(model.getHl7MsgNo());
                             hl7007.setPortAdress(socket.getRemoteSocketAddress().toString() );
                             opeonSocketLog(hl7007);
                         }else{
                             logger.error("Server socket is not conneted");
                         }
                        out = socket.getOutputStream();
                        //InputStream in =  socket.getInputStream();
                        out.write(transmitMsg.toString().getBytes());
                        // save file into directory             
                        // logging TABLE MESSAGE  data into file
                        if (params.isOutputOnFile()) {
                            //comment this line for performance issue
                            FileLogger.log2(transmitMsg.toString());
                        }
                      /** Write across the socket connection and flush the buffer */
                        out.flush();                                            
                        out.close();                        
                        // insert into record from Table HL7001 to  Table HL7003;

                        insertOrderModel(model);                        
                        msgCount++; 
                        logger.info("msgCount "+ msgCount);                     
                        if (Configuration.getConfig().getServerParams().getWaitingOption().equals("1")) {
                            try{
                                 Thread.sleep(1000);                            
                             }catch (InterruptedException e) {
                                logger.error("Wait for writing message into "+ e.getMessage());
                            }
                        }           
                }               
                    }           
          }catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }finally{
                try {
                    logger.info("finally block is executed in write method ");
                    socket.close();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            }
     }

在上面的写类中,首先我从表中读取记录,然后添加到列表中。如果记录存在,我打开了一个套接字连接,然后将数据写入端口并删除以下记录。但有时我会得到更多重复的记录

这一切都发生了两次。你正在为自己打开一个插座(为什么?);作家是被创造出来的,所以。。。你不应该通过TCP/IP与自己通信:在这一点上,你的设计出现了严重的问题。

您不需要为每个条目使用一个套接字。

使用您接受的一个套接字,将所有内容发送到该套接字,并且只有在完成后才将其关闭。

最新更新