【问题标题】:Can't send a message through Java socket without closing it无法通过Java套接字发送消息而不关闭它
【发布时间】:2012-05-06 17:09:02
【问题描述】:

我正在编写一个大型 Java 应用程序的服务器部分,用于使用 Java 套接字通过 TCP/IP 与客户端通信。客户端(用 PHP 编写)连接到服务器,发送 XML 格式的查询,然后服务器发回响应。查询-响应可以在单个连接中重复多次。

服务器端非常简单。它应该允许多个客户端连接,因此有一个线程监听并为每个接受的连接生成一个会话。会话由一个对象组成,该对象包含两个用于发送和接收的 LinkedBlockingQueue,两个用于使用这些队列发送和接收消息的线程以及一个处理线程。

问题是任何消息实际上只有在套接字关闭后才会传输。响应消息毫无问题地进入消息队列和 PrintStream.println() 方法,但仅当客户端关闭其一侧的连接时,wireshark 才会报告传输。在启用自动刷新或使用 flush() 的情况下创建 PrintStream 不起作用。关闭服务端的socket也不行,服务端还能正常工作并接收消息。

此外,在服务器端接收查询的客户端的当前实现工作正常,来自本地 Linux 虚拟机的echo -e "test" | socat - TCP4:192.168.37.1:1337 也是如此,但是当我远程登录到服务器并尝试发送一些东西时,服务器不会在我关闭 telnet 客户端之前收到任何内容,与上述相同的问题。

相关的服务器代码(整个应用程序太大,无法粘贴所有内容,我正在使用很多其他人的代码):

package Logic.XMLInterfaceForClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.HashSet;
import java.util.concurrent.LinkedBlockingQueue;

import Data.Config;
import Logic.Log;

public class ClientSession {

    /**
     * @author McMonster
     * 
     */
    public class MessageTransmitter extends Thread {

        private final Socket socket;
        private final ClientSession parent;

        private PrintStream out;

        /**
         * @param socket
         * @param parent
         */
        public MessageTransmitter(Socket socket, ClientSession parent) {
            this.socket = socket;
            this.parent = parent;
        }

        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            try {
                out = new PrintStream(socket.getOutputStream(), true);

                while (!socket.isClosed()) {
                    try {
                        String msg = parent.transmit.take();
                        // System.out.println(msg);
                        out.println(msg);
                        out.flush();
                    }
                    catch(InterruptedException e) {
                        // INFO: purposefully left empty to suppress spurious
                        // wakeups
                    }
                }

            }
            catch(IOException e) {
                parent.fail(e);
            }

        }

    }

    /**
     * @author McMonster
     * 
     */
    public class MessageReceiver extends Thread {

        private final Socket socket;
        private final ClientSession parent;

        private BufferedReader in;

        /**
         * @param socket
         * @param parent
         */
        public MessageReceiver(Socket socket, ClientSession parent) {
            this.socket = socket;
            this.parent = parent;
        }

        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                while (!socket.isClosed()) {
                    String message = "";
                    String line;

                    while ((line = in.readLine()) != null) {
                        message = message + line + "\n";
                    }

                    if(message != "") {
                        parent.receive.offer(message.toString());
                    }
                }
            }
            catch(IOException e) {
                parent.fail(e);
            }

        }
    }

    public final LinkedBlockingQueue<String> transmit = new LinkedBlockingQueue<>();
    public final LinkedBlockingQueue<String> receive = new LinkedBlockingQueue<>();

    private final XMLQueryHandler xqh;
    private final Socket socket;

    private String user = null;
    private HashSet<String> privileges = null;

    /**
     * @param socket
     * @param config
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public ClientSession(Socket socket, Config config)
            throws IOException,
            IllegalArgumentException {
        // to avoid client session without the client
        if(socket == null) throw new IllegalArgumentException("Socket can't be null.");

        this.socket = socket;

        // we do not need to keep track of the two following threads since I/O
        // operations are currently blocking, closing the sockets will cause
        // them to shut down
        new MessageReceiver(socket, this).start();
        new MessageTransmitter(socket, this).start();

        xqh = new XMLQueryHandler(config, this);
        xqh.start();
    }

    public void triggerTopologyRefresh() {
        xqh.setRefresh(true);
    }

    public void closeSession() {
        try {
            xqh.setFinished(true);
            socket.close();
        }
        catch(IOException e) {
            e.printStackTrace();
            Log.write(e.getMessage());
        }
    }

    /**
     * Used for reporting failures in any of the session processing threads.
     * Handles logging of what happened and shuts down all session threads.
     * 
     * @param t
     *            cause of the failure
     */
    synchronized void fail(Throwable t) {
        t.printStackTrace();
        Log.write(t.getMessage());
        closeSession();
    }

    synchronized boolean userLogin(String login, HashSet<String> privileges) {
        boolean success = false;

        if(!privileges.isEmpty()) {
            user = login;
            this.privileges = privileges;
            success = true;
        }

        return success;
    }

    public synchronized boolean isLoggedIn() {
        return user != null;
    }

    /**
     * @return the privileges
     */
    public HashSet<String> getPrivileges() {
        return privileges;
    }
}

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    它与发送根本没有任何关系。更准确地说,如果您阅读直到流结束,则在对等端通过关闭套接字结束流之前,您不会得到流的结束。

    这是一个重言式。

    【讨论】:

      【解决方案2】:

      我可以理解为什么在关闭套接字之前服务器没有收到任何消息——这似乎是设计的。 in.readLine() 只会在到达流的末尾时返回 null,对于 TCP 套接字流,这意味着当套接字关闭时。如果您希望 readLine() 循环在此之前返回,则循环中的代码必须使用您在 TCP 之上使用的任何协议来检测消息的结尾以定义消息。

      【讨论】:

      • 你说得对,我认为这可能是所有这些都无法正常工作的原因。我将编写一些可接受的 XML 消息检测代码,看看它是否能修复它。
      • 我添加了 XML 验证来代替读取一行并检查是否为空,现在一切正常。问题是它仅在关闭连接后才收到查询,因此无法在同一连接中发送响应。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多