简体   繁体   中英

Communication between Java programs

I'm trying to learn how to do deal with networks in Java 8, and I'm trying to make a client program communicate with a server one. The client is asked a string, which is sent to the server, and the server sends it back in upper characters.

I can't get my server part to work, it simply won't write anything except the fact that the connection is made. Could someone explain what's wrong with my code ?

Server :

public static void main(String[] args) throws IOException {
    int listenPort = 9000;
    ServerSocket listenSocket = new ServerSocket(listenPort);
    Socket socket = listenSocket.accept();

    System.out.println("Connexion réussie !");

    InputStream inputStream = socket.getInputStream();
    OutputStream outputStream = socket.getOutputStream();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
    DataOutputStream output = new DataOutputStream(outputStream);

    String line = null;

    System.out.println("test : " + buffer.readLine());

    while((line = buffer.readLine()) != null) {
        System.out.println("Message reçu : " + line);
        System.out.println("Message envoyé : " + line.toUpperCase());
        output.writeUTF(line.toUpperCase());

        if(line.equals("stop")) {
            socket.close();
            listenSocket.close();
        }
    }
}

Client side :

public static void main(String[] args) throws IOException, UnknownHostException {
    Socket socket = new Socket("127.0.0.1", 9000);

    InputStream inputStream = socket.getInputStream();
    OutputStream outputStream = socket.getOutputStream();
    DataInputStream input = new DataInputStream(inputStream);
    DataOutputStream output = new DataOutputStream(outputStream);

    BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));

    String line = null;

    while((line = buffer.readLine()) != null) {
        System.out.println("Message envoyé : " + line);
        output.writeChars(line);
        System.out.println("Message reçu : " + input.readUTF());

        if(line.equals("stop")) {
            break;
        }
    }

    socket.close();

}

Inside your client method, you call output.writeChars(line) inside the while loop, this means that you send something to the server after the server send something to you.

Change your client code as follows:

String line = "What a wonderful line";
System.out.println("Message envoyé : " + line);
output.writeChars(line);

while((line = buffer.readLine()) != null) {
    System.out.println("Message reçu : " + input.readUTF());
}

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