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

时间:2012-07-29 05:59:59

标签: java

我有一个程序可以从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();
                }
            }
     }

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

2 个答案:

答案 0 :(得分:2)

这一切都发生了两次。你正在打开一个插座给你自己(为什么?)所以另一对读卡器&amp;编写器是创建的,所以...你不应该通过TCP / IP与自己沟通:此时你的设计存在严重的问题。

答案 1 :(得分:2)

每个条目都不需要套接字。

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