简体   繁体   中英

No response received from the server

I can't receive a response from the server. When I start the client and the server nothing happens.

Here is the Server Code

public class Server {

    public static void main(String[] zero) throws IOException {
        ServerSocket socketServer;
        Socket socketDuServer;
        PrintWriter out;
        BufferedReader in;
        socketServer = new ServerSocket(2009);
        socketDuServer = socketServer.accept();
        in = new BufferedReader(new InputStreamReader(socketDuServer.getInputStream()));
        String message = in.readLine();
        out = new PrintWriter(socketDuServer.getOutputStream(), true);
        String numberMessage = "The Number of ET est:" + StringToArrayChar(message);
        System.out.println(numberMessage);
        out.print(numberMessage);
        out.flush();
        socketDuServer.close();
        socketServer.close();
    }

    public static int StringToArrayChar(String s) {
        int c = 0, k = 0;
        char[] charArray = s.toCharArray();
        for (int j = 0; j < s.length(); j++) {
            if (charArray[j] == 'e') {
                k = j + 1;
                if (charArray[k] == 't') {
                    c++;
                }
            }
        }
        return c;
    }
}

and here is the Client Code

public class Client {

    public static void main(String[] args) throws IOException {
        Socket socket;
        BufferedReader in;
        PrintWriter out;
        String message;
        socket = new Socket(InetAddress.getLocalHost(), 2009);
        out = new PrintWriter(socket.getOutputStream(), true);
        out.print("helloet");
        out.flush();
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        message = in.readLine();
        System.out.println(message);
        socket.close();
    }
}

Your server tries to receive a line but your client never sends a line.

There is no way to fix this problem. Why? Because we cannot tell whether the server is incorrect in trying to receive a line or the client is incorrect in not sending a line. The only we could tell is by consulting the specification for the protocol which explains how the server and client exchange data. And there isn't one. Fail.

Please take a huge step back. Read the specifications for a few protocols layered on top of TCP such as HTTP, IRC and SMTP. Then, before you start writing code that uses TCP, spend the time to clearly document your protocol. This will avoid mistakes like this one, and the hundreds of others people who first try to use TCP inevitably make.

I know this sounds like a huge pain. But trust me, there are dozens of similar mistakes just waiting for you to make them.

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