Java客户端/服务器双向套接字无法正常工作

时间:2013-06-06 17:54:00

标签: java sockets client-server socketserver

我正在编写一个Java客户端/服务器应用程序,它将在每个程序之间来回传递2个映射。客户端填充初始映射并将其发送到服务器。服务器按预期接收映射并显示数据。然后,服务器构建响应映射,并将其返回给客户端。客户端按预期接收映射并显示数据。一切似乎都很好。现在,客户端使用更多数据清除并重新填充地图,并将地图发送到服务器。服务器按预期接收它,构建并发送响应映射。客户端读取地图的“objectinputstream”,但地图现在为空。客户端使用更多数据清除并重新填充地图,并再次将地图发送到服务器。服务器似乎接收到地图,但显示的数据是第二次成功传输接收的数据,而不是当前数据。任何人都可以了解这里发生的事情吗?所有人都非常感谢!

这是服务器的日志:

- awaiting connection
- about to readobject
- read this>I-InkjetBadLabel = `Send`
- read this>I-LogoPakBadLabel = `Send`
- read this>I-InkjetBadLabelAck = `Response`
- read this>I-LogoPakBadLabelAck = `Response`
- writing this>I-InkjetBadLabel = `Send`
- writing this>I-LogoPakBadLabel = `Send`
- writing this>I-InkjetBadLabelAck = `Response`
- writing this>I-LogoPakBadLabelAck = `Response`
- wrote socket
- about to readobject
- read this>InkjetBadLabel = `False0`
- read this>LogoPakBadLabel = `False0`
- writing this>InkjetBadLabel = `False0`
- writing this>LogoPakBadLabel = `False0`
- wrote socket
- about to readobject
- read this>InkjetBadLabel = `False0`
- read this>LogoPakBadLabel = `False0`
- writing this>InkjetBadLabel = `False0`
- writing this>LogoPakBadLabel = `False0`
- wrote socket
- about to readobject
- read this>InkjetBadLabel = `False0`
- read this>LogoPakBadLabel = `False0`
- writing this>InkjetBadLabel = `False0`
- writing this>LogoPakBadLabel = `False0`
- wrote socket
- about to readobject
- read this>InkjetBadLabel = `False0`
- read this>LogoPakBadLabel = `False0`
- writing this>InkjetBadLabel = `False0`
- writing this>LogoPakBadLabel = `False0`
- wrote socket

这是客户的日志:

-  PLC_socket. open!!
-  istream = new ObjectInputStream
-  ostream = new ObjectOutputStream
-  sending externalProgramCommInitializeMap
-  externalProgramCommInitializeMap =>I-InkjetBadLabel = `Send`
-  externalProgramCommInitializeMap =>I-LogoPakBadLabel = `Send`
-  externalProgramCommInitializeMap =>I-InkjetBadLabelAck = `Response`
-  externalProgramCommInitializeMap =>I-LogoPakBadLabelAck = `Response`
-  ostream.writeObject
-  istream.readObject()  1 
-   initialize received externalProgramCommBitMapOutOfPFC  response -
-  externalProgramCommBitMap =>I-InkjetBadLabel = `Send`
-  externalProgramCommBitMap =>I-LogoPakBadLabel = `Send`
-  externalProgramCommBitMap =>I-InkjetBadLabelAck = `Response`
-  externalProgramCommBitMap =>I-LogoPakBadLabelAck = `Response`
-  xx=0
-  externalProgramCommBitMapIntoPFC.clear 
-  externalProgramCommBitMapIntoPFC =>InkjetBadLabel = `False0`
-  externalProgramCommBitMapIntoPFC =>LogoPakBadLabel = `False0`
-  writing map!
-  ostream.flush
-  done writing
-  data - istream.readObject()  
-  data - received externalProgramCommBitMapOutOfPFC  response
-   !!!!!! RESPONSE MAP IS EMPTY !!!!!!
-  xx=1
-  externalProgramCommBitMapIntoPFC.clear 
-  externalProgramCommBitMapIntoPFC =>InkjetBadLabel = `False1`
-  externalProgramCommBitMapIntoPFC =>LogoPakBadLabel = `False1`
-  writing map!
-  ostream.flush
-  done writing
-  data - istream.readObject()  
-  data - received externalProgramCommBitMapOutOfPFC  response
-   !!!!!! RESPONSE MAP IS EMPTY !!!!!!
-  xx=2
-  externalProgramCommBitMapIntoPFC.clear 
-  externalProgramCommBitMapIntoPFC =>InkjetBadLabel = `False2`
-  externalProgramCommBitMapIntoPFC =>LogoPakBadLabel = `False2`
-  writing map!
-  ostream.flush
-  done writing
-  data - istream.readObject()  
-  data - received externalProgramCommBitMapOutOfPFC  response
-   !!!!!! RESPONSE MAP IS EMPTY !!!!!!
-  xx=3
-  externalProgramCommBitMapIntoPFC.clear 
-  externalProgramCommBitMapIntoPFC =>InkjetBadLabel = `False3`
-  externalProgramCommBitMapIntoPFC =>LogoPakBadLabel = `False3`
-  writing map!
-  ostream.flush
-  done writing
-  data - istream.readObject()  
-  data - received externalProgramCommBitMapOutOfPFC  response
-   !!!!!! RESPONSE MAP IS EMPTY !!!!!!

这是我的客户计划:

package com.agfa.Verify;

import java.io.*;
import java.net.*;
import java.net.UnknownHostException;
import java.util.*;
import org.apache.log4j.Logger;

public class testVerifyScannedLabels implements Serializable {

    private static final long serialVersionUID = 1L;
    private final Logger log = Logger.getLogger(testVerifyScannedLabels.class.getSimpleName());
    private boolean debugEnabled = false;
    private Map<String, String> externalProgramCommBitMapIntoPFC = new LinkedHashMap<String, String>();
    private Map<String, String> externalProgramCommBitMapOutOfPFC = new LinkedHashMap<String, String>();
    private Socket PLC_socket = null;
    private Map<String, String> externalProgramCommInitializeMap = new LinkedHashMap<String, String>();
    private ObjectOutputStream ostream = null;
    private ObjectInputStream istream = null;
    private List<String> errorMessages = new ArrayList<String>();

    private void initialize() {
        externalProgramCommInitializeMap.put("I-InkjetBadLabel", "Send");
        externalProgramCommInitializeMap.put("I-LogoPakBadLabel", "Send");
        externalProgramCommInitializeMap.put("I-InkjetBadLabelAck", "Response");
        externalProgramCommInitializeMap.put("I-LogoPakBadLabelAck", "Response");
    }

    public testVerifyScannedLabels() {

        initialize();

        /***********************************************************************
         * sockets client for PLC Communicator
         **********************************************************************/
        if (PLC_socket == null) {
            log.debug("PLC_socket == null");
            try {
                istream = null;
                ostream = null;

                PLC_socket = new Socket(InetAddress.getLocalHost(), 60103);
                PLC_socket.setKeepAlive(true);

                log.debug("PLC_socket opened on port 60103");
            } catch (NumberFormatException x) {
                log.warn("PLC_CommMapPort-NumberFormatException Exception! " + x.getMessage());
            } catch (ConnectException x) {
                log.warn("PLC_CommMapPort-Connection Exception! " + x.getMessage());
            } catch (UnknownHostException x) {
                log.warn("PLC_CommMapPort-UnknownHostException Exception! " + x.getMessage());
            } catch (IOException x) {
                log.warn("PLC_CommMapPort-IOException Exception! " + x.getMessage());
            }
        }

        if (PLC_socket == null) {
            log.error("PLC_socket was not established!");
            istream = null;
            ostream = null;
        } else {
            log.debug("PLC_socket not null!!!");
            try { // Socket client..

                if (PLC_socket.isConnected() && !PLC_socket.isClosed()) {
                    log.info("PLC_socket. open!!");
                    if (istream == null) {
                        log.debug("istream = new ObjectInputStream");
                        istream = new ObjectInputStream(PLC_socket.getInputStream());
                    }
                    if (ostream == null) {
                        log.debug("ostream = new ObjectOutputStream");
                        ostream = new ObjectOutputStream(PLC_socket.getOutputStream());
                        log.debug("sending externalProgramCommInitializeMap");
                        final Iterator<Map.Entry<String, String>> it = externalProgramCommInitializeMap
                                .entrySet().iterator();
                        while (it.hasNext()) {
                            final Map.Entry<String, String> pairs = it.next();
                            log.debug("externalProgramCommInitializeMap =>" + pairs.getKey()
                                    + " = `" + pairs.getValue() + "`");
                        }
                        log.debug("ostream.writeObject");
                        ostream.writeObject(externalProgramCommInitializeMap);

                        log.debug("istream.readObject()  1 ");
                        externalProgramCommBitMapOutOfPFC = (Map<String, String>) istream
                                .readObject();
                        log.debug(" initialize received externalProgramCommBitMapOutOfPFC  response -");
                        final Iterator<Map.Entry<String, String>> rit = externalProgramCommBitMapOutOfPFC
                                .entrySet().iterator();
                        while (rit.hasNext()) {
                            final Map.Entry<String, String> pairs = rit.next();
                            log.debug("externalProgramCommBitMap =>" + pairs.getKey() + " = `"
                                    + pairs.getValue() + "`");
                        }
                    }

                    for (int xx = 0; xx < 100; xx++) { // for testing only
                        log.debug("xx=" + xx);
                        log.debug("externalProgramCommBitMapIntoPFC.clear ");
                        externalProgramCommBitMapIntoPFC.clear();
                        externalProgramCommBitMapIntoPFC.put("InkjetBadLabel", "False" + xx);
                        externalProgramCommBitMapIntoPFC.put("LogoPakBadLabel", "False" + xx);
                        externalProgramCommBitMapOutOfPFC.clear();

                        for (String line : errorMessages) {
                            log.info("build externalProgramCommBitMapIntoPFC " + line.toUpperCase());
                            if (line.toUpperCase().contains("INKJET")) {
                                log.debug("in ink");
                                externalProgramCommBitMapIntoPFC.put("InkjetBadLabel", "True" + xx);
                            }
                            if (line.toUpperCase().contains("LOGOPAK")) {
                                log.debug("in logo");
                                externalProgramCommBitMapIntoPFC
                                        .put("LogoPakBadLabel", "True" + xx);
                            }
                        }

                        final Iterator<Map.Entry<String, String>> wit = externalProgramCommBitMapIntoPFC
                                .entrySet().iterator();
                        while (wit.hasNext()) {
                            final Map.Entry<String, String> pairs = wit.next();
                            log.debug("externalProgramCommBitMapIntoPFC =>" + pairs.getKey()
                                    + " = `" + pairs.getValue() + "`");
                        }

                        log.debug("writing map!");
                        ostream.writeObject(externalProgramCommBitMapIntoPFC);
                        log.debug("ostream.flush");
                        ostream.flush();
                        log.debug("done writing");
                        log.debug("data - istream.readObject()  ");
                        externalProgramCommBitMapOutOfPFC = (Map<String, String>) istream
                                .readObject();
                        log.debug("data - received externalProgramCommBitMapOutOfPFC  response");
                        final Iterator<Map.Entry<String, String>> rit = externalProgramCommBitMapOutOfPFC
                                .entrySet().iterator();
                        if (rit.hasNext()) {
                            while (rit.hasNext()) {
                                final Map.Entry<String, String> pairs = rit.next();
                                log.debug("externalProgramCommBitMap =>" + pairs.getKey() + " = `"
                                        + pairs.getValue() + "`");
                            }
                        } else
                            log.debug(" !!!!!! RESPONSE MAP IS EMPTY !!!!!!");
                        Thread.sleep(4000L);
                        /**/} // end for testing ..
                } else {
                    log.error("VerifyScannedLabels unable to connect to PLC_Datacomm via Sockets");
                }
                // end of Socket client
            } catch (UnknownHostException e) {
                log.error("VerifyScannedLabels unable to connect to PLC_Datacomm via Sockets  "
                        + e.getMessage());
                PLC_socket = null;
            } catch (IOException e) {
                log.error("VerifyScannedLabels unable to connect to PLC_Datacomm via Sockets "
                        + e.getMessage());
                PLC_socket = null;
            } catch (ClassNotFoundException e) {
                log.error("VerifyScannedLabels unable to connect to PLC_Datacomm via Sockets "
                        + e.getMessage());
                PLC_socket = null;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (debugEnabled) {
                log.debug("VerifyScannedLabels processing Ends.");
            }

            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        testVerifyScannedLabels vsl = new testVerifyScannedLabels();
    }
}    

这是我的服务器程序:

package com.agfa.sockets;

import java.net.*;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.io.*;

import org.apache.log4j.Logger;


public class testSocketThreadSendReceiveMap {
    private Logger log = Logger.getLogger(testSocketThreadSendReceiveMap.class.getSimpleName());
    private ServerSocket ssock = null;
    private Socket socket = null;
    private ObjectOutputStream ostream = null;
    private ObjectInputStream istream = null;
    private Map<String, String> dataMapIntoRemote = new LinkedHashMap<String, String>();
    private Map<String, String> dataMapFromRemote = new LinkedHashMap<String, String>();

    public static void main(String[] args) {

        testSocketThreadSendReceiveMap tSTSRM = new testSocketThreadSendReceiveMap();
    }

    @SuppressWarnings("unchecked")
    public testSocketThreadSendReceiveMap() {

        try {
            log.info("awaiting connection");
            ssock = new ServerSocket(60103);
            socket = ssock.accept();
            ostream = new ObjectOutputStream(socket.getOutputStream());
            istream = new ObjectInputStream(socket.getInputStream());

            while (true) {
                //log.debug("following is for testing - remove from production");
                /*
                 * in real life dataMapIntoRemote will be provided by parent
                 * Thread
                 */
                dataMapIntoRemote.clear();
                /****** remove above *****/

                dataMapFromRemote.clear();
                log.debug("about to readobject");
                dataMapFromRemote.putAll((Map<String, String>) istream.readObject());

                final Iterator<Map.Entry<String, String>> it = dataMapFromRemote.entrySet()
                        .iterator();
                while (it.hasNext()) {
                    final Map.Entry<String, String> pairs = it.next();
                    log.debug("read this>" + pairs.getKey() + " = `" + pairs.getValue() + "`");

                        //log.debug("following is for testing - remove from production");
                        /*
                         * in real life dataMapIntoRemote will be provided by
                         * parent Thread
                         */
                        dataMapIntoRemote.put(pairs.getKey(), pairs.getValue());
                        /****** remove above *****/

                }

                final Iterator<Map.Entry<String, String>> wit = dataMapIntoRemote.entrySet()
                        .iterator();
                while (wit.hasNext()) {
                    final Map.Entry<String, String> pairs = wit.next();
                    log.debug("writing this>" + pairs.getKey() + " = `" + pairs.getValue() + "`");
                }

                ostream.writeObject(dataMapIntoRemote);
                ostream.flush();
                log.debug("wrote socket");
            }
        } catch (IOException e) {
            log.error("SocketThreadSendReceiveMap-While(True).IOException! " + e.getMessage());
        } catch (Exception e) {
            log.error("SocketThreadSendReceiveMap-While(True).Exception! " + e.getMessage());

        }
        try {
            log.warn("SocketThreadSendReceiveMap.class socket.close");
            socket.close();
        } catch (IOException e) {
            log.error("SocketThreadSendReceiveMap-socket.close().IOException! " + e.getMessage());
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您还需要在致电ostream.reset()后立即致电ostream.flush()

ObjectOutputStream维护一个内部的引用映射,以便在您最终多次写入相同的引用时保存序列化时间,这就是您在发送映射时所执行的操作。在reset()之后调用flush()清除此内部引用表,并在下次调用时间writeObject(object)时使对象重新序列化,无论之前是否传入了相同的引用。