Danny
Danny

Reputation: 97

JAVA TCP client not printing and disconnecting

I have a TCP server and client, but the client never prints the last system.out and disconnects from server socket.

My client message loop:

for (int i = 1; i <= Integer.parseInt(args[2]); i++) {
    long messageTimeStart = System.currentTimeMillis();

    outToServer.write(MSG.getBytes());
    outToServer.flush();

    Thread.sleep((long) messageTimePerSecond);
    long messageTimeEnd = System.currentTimeMillis();
    long totalMessageTime = messageTimeEnd - messageTimeStart; //Meassure total packet transfer time.
    System.out.println("Message " + i + ": '" + MSG + "' sent in: " + totalMessageTime);

    elapsedTime += totalMessageTime;
}

while (true) {
    try {
        int msgLength = serverEcho.read(buf);
        if (msgLength == -1) {
            break;
        }
        String echoMessage = new String(buf);
        System.out.println("ECHO MESSAGE: " + echoMessage);
    } catch (IOException e) {
        System.out.println("Hot damn");
    }
}

System.out.printf(args[2] + " Messages sent in: " + elapsedTime + " milliseconds.");
outToServer.close();
serverEcho.close();
socket.close();

It never gets to the four last lines for some reason. And I have no Idea why.

If it matters, here is my Server class run method:

public void run() {
    try {
        while (true) {
            try {
                inFromClient = new DataInputStream(clientSocket.getInputStream());
                outToClient = new DataOutputStream(clientSocket.getOutputStream());

                //InputStream in = clientSocket.getInputStream();
                //DataInputStream dis = new DataInputStream(in);
                int msgLength = 0;

                msgLength = inFromClient.read(dataBuffer);

                String message = new String(dataBuffer);
                System.out.println("Message recieved: " + message);

                outToClient.write(message.getBytes(), 0, msgLength);
                outToClient.flush();
                System.out.println("Echo message sent: " + message);

            } catch (SocketException e) {
                System.out.println("Connection terminated by client.");
                break;
            }
        }

        clientSocket.close();
    } catch (IOException e) {
        System.out.println("Could not listen on port: " + clientSocket.getLocalPort());
        System.out.println("Client thread terminated.");
    }
}

Upvotes: 0

Views: 298

Answers (1)

Ant&#243;nio Ribeiro
Ant&#243;nio Ribeiro

Reputation: 4203

You already know the amount of data that the server will return to you since the server is returning the same information that the client is sending to him.

Therefore, you could try this approach:

Server

@Override
public void run() {
    ServerSocket serverSocket = null;
    Socket clientSocket = null;
    DataInputStream inFromClient = null;
    DataOutputStream outToClient = null;

    try {
        serverSocket = new ServerSocket(4321);
    } catch (IOException ioe) {
        System.out.println("Could not listen on port 4321. Cause: " + ioe);
        System.exit(-1);
    }

    System.out.println("#Server#listening on port 4321!");

    try {
        clientSocket = serverSocket.accept();
    } catch (IOException ioe) {
        System.out.println("Accept failed on port: 4321. Cause: " + ioe);
        System.exit(-1);
    }

    System.out.println("#Server#accepting connections on port 4321!");

    try {
        inFromClient = new DataInputStream(clientSocket.getInputStream());
        outToClient = new DataOutputStream(clientSocket.getOutputStream());
    } catch (IOException ioe) {
        System.out.println("Input and output streams creation failed. Cause: " + ioe);
        System.exit(-1);
    }

    System.out.println("#Server#created input and output streams!");

    byte[] dataBuffer = new byte[1024];

    try {
        while (true) {
            try {
                int msgLength = 0;

                msgLength = inFromClient.read(dataBuffer);

                String message = new String(dataBuffer);
                System.out.println("Message recieved: " + message);

                outToClient.write(message.getBytes(), 0, msgLength);
                outToClient.flush();
                System.out.println("Echo message sent: " + message);

            } catch (SocketException e) {
                System.out.println("Connection terminated by client.");
                break;
            }
        }

        clientSocket.close();
    } catch (IOException e) {
        System.out.println("Could not listen on port: " + clientSocket.getLocalPort());
        System.out.println("Client thread terminated.");
    } finally {
        try {
            outToClient.close();
            inFromClient.close();
            clientSocket.close();
            serverSocket.close();
        } catch (IOException ioe) {
            System.out.println("Unable to close streams and sockets. Cause: " + ioe);
            System.exit(-1);
        }
    }
}

Client

@Override
public void run() {
    String MSG = "Hello from client, mister server!";
    Socket socket = null;
    DataOutputStream outToServer = null;
    DataInputStream inFromServer = null;

    try {
        socket = new Socket("localhost", 4321);
    } catch (IOException ioe) {
        System.out.println("Unable to connect with host: localhost. Cause: " + ioe);
        System.exit(1);
    }

    System.out.println("@Client@connected with server localhost on port 4321!");

    try {
        outToServer = new DataOutputStream(socket.getOutputStream());
        inFromServer = new DataInputStream(socket.getInputStream());
    } catch (IOException ioe) {
        System.out.println("Input and output streams creation failed. Cause: " + ioe);
        System.exit(-1);
    }

    System.out.println("@Client@created input and output streams!");

    long messageTimePerSecond = 3000;
    long elapsedTime = 0;

    try {
        for (int it = 0; it < 5; it++) {
            long messageTimeStart = System.currentTimeMillis();

            outToServer.write(MSG.getBytes());
            outToServer.flush();

            Thread.sleep((long) messageTimePerSecond);
            long messageTimeEnd = System.currentTimeMillis();
            // Measure total packet transfer time.
            long totalMessageTime = messageTimeEnd - messageTimeStart;
            System.out.println("Message " + it + ": '" + MSG + "' sent in: " + totalMessageTime);

            elapsedTime += totalMessageTime;
        }

        byte[] dataBuffer = new byte[1024];
        String echoMessage = "";
        int msgLength = 0;
        int totalData = MSG.length();
        boolean finish = false;

        while (!finish) {
            try {
                msgLength = inFromServer.read(dataBuffer);
                echoMessage += new String(dataBuffer, 0, msgLength);

                if (echoMessage.length() == totalData) {
                    finish = true;
                }

                System.out.println("ECHO MESSAGE: " + echoMessage);
            } catch (IOException e) {
                System.out.println("Hot damn");
            }
        }
    } catch (IOException | InterruptedException e) {
        System.out.println("Something bad happened. Cause: " + e);
        System.exit(-1);
    } finally {
        System.out.printf("5 Messages sent in: " + elapsedTime + " milliseconds.");
        try {
            inFromServer.close();
            outToServer.close();
            socket.close();
        } catch (IOException ioe) {
            System.out.println("Unable to close streams and socket. Cause: " + ioe);
            System.exit(-1);
        }
    }
}

Both Server and Client implement Runnable and your main class can be like this:

public class ClientServerMain {

    public static void main(String[] args) {
        Thread server = new Thread(new Server());
        server.start();
        Thread client = new Thread(new Client());
        client.start();
    }
}

Upvotes: 2

Related Questions