简体   繁体   中英

BufferedReader Pending for Request/Response Socket Connection

I am trying to build a simple request/response server.

Client send a message to Server. Then, the server response a message to client.

Server-side Code

package com.techoffice.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

public class TcpServerAppl {

    static int port = 1010;
    static ServerSocket serverSocket;
    static {
        try {
            serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        System.out.println("Server is running on " + port);
        while(true){
            Socket socket = null;
            try{        
                socket = serverSocket.accept();
                System.out.println("Someone is connecting to the server");
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();

                PrintWriter printWriter = new PrintWriter(os);

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

                // read message from client 
                String line = bufferedReader.readLine();
                while(line != null && line.length() > 0){
                    System.out.println(line);
                    line = bufferedReader.readLine();
                }
//              reader.close();

                // send message to client
                System.out.println("Server starts sending message to client");
                printWriter.println("This is a message sent from server");
                printWriter.flush();
//              printWriter.close();

            } catch(Exception e){
                System.err.println(e.getMessage());
            } finally {
                if (socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.err.println(e.getMessage());
                    }
                }
            }
        }

    }
}

Client-side code

package com.techoffice.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

public class TcpClientAppl {
    public static void main(String[] args) throws UnknownHostException, IOException{
        // start socket connection
        Socket socket = SocketFactory.getDefault().createSocket("localhost", 1010);
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // send message to server
        printWriter.println("Send Message From Client" );
        printWriter.flush();
//      printWriter.close();

        // read message from server
        System.out.println("Client starts reading from Server");
        String line = bufferedReader.readLine();
        while(line != null && line.length() > 0){
            System.out.println(line);
            line = bufferedReader.readLine();
        }
//      bufferedReader.close();

        // close scoket connection
        socket.close();
    }
}

The Server is blocked at the Buffered Reader. However, if I tried to close the Buffered Reader by closing in Print Writer in Client, the Client throw an exception of "Connection Closed".

It is known that closing in PrintWriter or BufferedReader would close the socket connection.

Update

Specifying a End of Request/Message would be one of solution. But in this case, I would not want to have an End of Request. I just want to have response for a request no matter no many line is in the request.

The client throw an exception of 'connection closed'

No it doesn't. If you uncomment the printWriter.close() line it will throw an exception ' socket closed'.

But to your real problem. The server reads lines until end of stream before it sends anything: end of stream will never occur until the peer closes the connection; and the peer isn't closing the connection, except as above; so it will never send anything and just stay blocked in readLine() ; so the client will block forever in readLine() too.

As this is evidently an echo server, it should echo every line as it is received.

Question is missing exception thrown by client side. Maybe try to close everything (reader,writer) on server-side after your communication is done. BTW. you don't need to call flush before calling close. Also you can use try-catch-withResources with socket on server side

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