简体   繁体   English

java中的TCP套接字

[英]TCP socket in java

In this fragment of code, the client sends a String to the Server. 在此代码片段中,客户端将String发送到服务器。 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 : Ecrire une chaine de caractere:
teste 泰斯特
i want to reverse : teste 我想逆转:teste
ch is sent ch被发送

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. 因此,即使accept方法成功通过,服务器端也会在从客户端读取输入的步骤中保持挂起状态。

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. 刷新确保在调用flush()之前写入writer的任何内容都写入底层流,而不是放在某个内部缓冲区中。

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 ) (请参阅: 如何为PrintWriter使用flush

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 . 和世界上的句子Hello程序员一起插图。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM