JAVA TCP客户端无法打印和断开连接

时间:2016-02-14 14:13:46

标签: java sockets tcp

我有一个TCP服务器和客户端,但客户端从不打印最后一个system.out并断开与服务器套接字的连接。

我的客户端消息循环:

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

由于某种原因,它永远不会到达最后四行。我不明白为什么。

如果重要,这是我的Server类运行方法:

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.");
    }
}

1 个答案:

答案 0 :(得分:2)

您已经知道服务器将返回给您的数据量,因为服务器返回了客户端发送给他的相同信息。

因此,您可以尝试这种方法:

服务器

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

<强>客户端

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

服务器客户端都实现Runnable,您的主类可以是这样的:

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