Java 客户端/服务器双向套接字不工作

标签 java sockets client-server socketserver

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

这是服务器的日志:

- 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());
        }
    }
}

最佳答案

您还需要在调用 ostream.flush() 后立即调用 ostream.reset()

ObjectOutputStream 维护它所写入的引用的内部映射,以便在您最终多次写入相同的引用(这就是您发送映射时所做的事情)时节省序列化时间。在 flush() 之后调用 reset() 会清除此内部引用表,并导致下次调用 writeObject(object) 时重新序列化对象,无论之前是否传入了相同的引用。

关于Java 客户端/服务器双向套接字不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968892/

相关文章:

node.js - socket.io 获取所有已连接客户端数量的房间

python - 连接到本地主机上的套接字

sockets - IPv6套接字创建

design-patterns - 用于在线交互的客户端-服务器消息传递协议(protocol)

java - 将结果集写入具有排序输出的文件

java - OpenGL:除以 w 零

javascript - 如何将自定义用户数据添加到 meteor 帐户

java - 在使用 java 的客户端服务器的 Protocol Buffer 中需要帮助

java - Hadoop 1.2.1 的源附件

java - BitSet(JAVA) 在埃拉托斯特尼筛法的实现中抛出 outofBoundsException