简体   繁体   中英

Java TCP/IP Server will not pass on the output to clients

This is part off a bigger application, that is why the send methods uses String-Arrays, which are generated by another pieve of Software. This worked before. This piece is code is designed to accept one client connection at a time on the specified port and send Data to them. FOr some reason the data written to out will never be seen by the clients, i even tried printwriter, ArrayOutputstream and many more. At this point i have no idea on what is wrong here. I have wasted several hours on debugging and rewritting without any success. I tried making clients with simple echo, reading line-by-line etc. But no matter what i do, they never see any output. I Would really appreciate your suggestions.

The while(true) loop was added for testing purposes

 import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    public class ServerStream implements Runnable {
        private ServerSocket serverSocket;
        private Socket socket;
        private volatile boolean cancel = false;
        private int port = 0;
        final static Logger logger = LoggerFactory.getLogger("odc");
        private BufferedOutputStream out;
    
        public ServerStream(ServerSocket serverSocket) {
            this.serverSocket = serverSocket;
            this.port = serverSocket.getLocalPort();
        }
    
        @Override public void run() {
            logger.info("Opening Serversocket at port {}", port);
            try {
                while (!cancel) {
                    if (this.socket != null && !this.socket.isClosed()) {
                        socket.setKeepAlive(true);
                    }
                    socket = serverSocket.accept();
                    logger.info("Client connected to Serversocket! at {}", port);
                    out = new BufferedOutputStream(socket.getOutputStream());
                    String[] a = new String[1];
                    a[0] = "AAAAAAAA";
                    while (true) {
                        send(a);
                        Thread.sleep(100);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                e.printStackTrace();
            }
        }
    
        public boolean isConnected() {
            return socket.isConnected();
        }
    
        public void send(String[] arg) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < arg.length; i++) {
                builder.append(arg[i]);
            }
            try {
                out = new BufferedOutputStream(socket.getOutputStream());
                out.write(builder.toString().getBytes());
                out.flush();
                System.out.println(builder.toString());
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        public void cancel() {
            cancel = true;
            try {
                serverSocket.close();
                if (socket != null) {
                    out.flush();
                    out.close();
                    socket.close();
                }
    
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }
        public int getPort() {
            return port;`enter code here`
        }
        public void setPort(int por`enter code here`t) {
            this.port = port;
        }
    }

I am not sure how your code gets called, so I am assuming you will be using the Runnable's run() method.

You create a BufferedOutputStream, then call send(). Send creates another BufferedOutputStream and writes a few A s. After all this stream gets flushed, but I believe in total you are creating too many BufferedOutputStreams. Since you do not close any of them I suspect they would be clogging up your memory until the garbage collector would kick in.

Instead try to only create one BufferedOutputStream outside the loop, then reuse that and flush regularly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM