简体   繁体   中英

TCP socket in java

In this fragment of code, the client sends a String to the Server. The server reverses it and resends it to the client.

  • But, The client did not receive any string.
  • Or, maybe the server does not receive the string to reverse.

Server code:

public class Serveur {
    public static void main(String[] args) {
        ServerSocket sock = null;
        Socket link = null;
        BufferedReader input = null;
        PrintWriter output = null;

        try {
            sock = new ServerSocket(1234);
            link = sock.accept();
            input = new BufferedReader(new InputStreamReader(link.getInputStream()));
            output = new PrintWriter(link.getOutputStream());
            String str, rstr;
            while(true){
                System.out.println("entered while loop");
                str = input.readLine();
                System.out.println("we received : " + str);
                rstr="";
                for (int i = 0; i < str.length(); i++)
                    rstr = str.charAt(i) + rstr;
                System.out.println("we will send to the client : " + rstr);
                output.print(rstr);
                System.out.println("sent");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Client Code:

public class Client {

    public static void main(String[] args) {
        Socket sock = null;
        PrintWriter output = null;
        BufferedReader input = null;

        try { 
            sock = new Socket(InetAddress.getLocalHost(), 1234);
            output = new PrintWriter(sock.getOutputStream());
            input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String str;
            Scanner s = new Scanner(System.in);
            while(true){
                System.out.println("Ecrire une chaine de caractere : ");
                str = s.nextLine();
                System.out.println("i want to reverse : " + str);    
                output.println(str);
                       System.out.println("ch is sent");
                       String rr = input.readLine();
                System.out.print(rr);
                       System.out.println("reversed word is received");
            }
        } catch (UnknownHostException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

Server Output:

entered while loop

Client Output:

Ecrire une chaine de caractere :
teste
i want to reverse : teste
ch is sent

The only problems your are facing are related to flushing your output streams. Because of that, even though the accept method passes succesfully the server side stays pending at the step of reading the input from the client.

Flushing makes sure that anything written to the writer prior to the call to flush() is written to the underlying stream, rather than sit in some internal buffer.

The method comes in handy in several types of circumstances:

  • If another process (or thread) needs to examine the file while it's being written to, and it's important that the other process sees all the recent writes.

  • If the writing process might crash, and it's important that no writes to the file get lost.

  • If you're writing to the console, and need to make sure that every message is shown as soon as it's written

(See: How to use flush for PrintWriter )

I updated your code accordingly and it is working.

The updated server code:

public class Serveur {
    public static void main(String[] args) {
        ServerSocket sock = null;
        Socket link = null;
        BufferedReader input = null;
        PrintWriter output = null;

        try {
            sock = new ServerSocket(9890);
            link = sock.accept();
            input = new BufferedReader(new InputStreamReader(link.getInputStream()));
            output = new PrintWriter(link.getOutputStream());
            String str, rstr;
            while(true){
                System.out.println("entered while loop");
                str = input.readLine();
                System.out.println("we received : " + str);
                rstr="";
                for (int i = 0; i < str.length(); i++)
                    rstr = str.charAt(i) + rstr;
                System.out.println("we will send to the client : " + rstr);
                output.println(rstr);

                output.flush();
                System.out.println("sent");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

}

The updated client code:

public class Client {
    public static void main(String[] args) {
        Socket sock = null;
        PrintWriter output = null;
        BufferedReader input = null;

        try { 
            sock = new Socket(InetAddress.getLocalHost(), 9890);
            output = new PrintWriter(sock.getOutputStream());
            input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String str;
            Scanner s = new Scanner(System.in);
            while(true){
                System.out.println("Ecrire une chaine de caractere : ");
                str = s.nextLine();
                System.out.println("i want to reverse : " + str);    
                output.println(str);
                output.flush();
                       System.out.println("ch is sent");
                       String rr = input.readLine();
                System.out.print(rr);
                       System.out.println("reversed word is received");
            }
        } catch (UnknownHostException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            //Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
}

}

And the illustration with the sentence Hello programmers of the world .

在此输入图像描述

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