printstream vs printwriter vs DataOutStream vs outputstream

dddzy1tm  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(323)

希望你没事,我开始学习java socket编程和处理客户机服务器,我在理解io库的不同类和对象时遇到了很多问题,我真的需要有人帮我总结一下。printstream,printwriter,dataoutputstream,outputstream之间的区别是什么,我猜还有outputstreamwriter。我们什么时候使用每一个(举例说明会很好)?如果我要求太多,请回复我一个youtube视频或一些外部链接。请不要引用eclipse的话来回复我。下面是我一直在编写的一个代码,它使客户机的消息变成大写:
◙ 服务器代码:

  1. package clientServer;
  2. import java.net.*;
  3. import java.io.*;
  4. public class Server{
  5. public static void main(String[] args) throws IOException{
  6. ServerSocket incoming = new ServerSocket(9999);
  7. System.out.println("Connecting...");
  8. Socket client = incoming.accept();
  9. System.out.println("Client is connected");
  10. String messageIn,messageOut;
  11. BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  12. messageIn = in.readLine();
  13. messageOut = messageIn.toUpperCase();
  14. PrintStream outnet = new PrintStream(client.getOutputStream());
  15. outnet.print(messageOut + "\n");
  16. outnet.flush();
  17. outnet.close();
  18. client.close();
  19. incoming.close();
  20. }
  21. }

◙ 客户代码:

  1. package clientServer;
  2. import java.net.*;
  3. import java.io.*;
  4. public class Client{
  5. public static void main(String[] args) throws IOException{
  6. Socket client = new Socket("localhost",9999);
  7. System.out.println("Connected to the Server");
  8. PrintStream outnet = new PrintStream(client.getOutputStream());
  9. String message;
  10. BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
  11. BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
  12. System.out.print("Veillez tappez quelque chose: ");
  13. message = input.readLine();
  14. outnet.print(message + "\n");
  15. // outnet.flush();
  16. // outnet.close();
  17. message = in.readLine();
  18. System.out.println("Server: " + message);
  19. client.close();
  20. }
  21. }

当我使用printstream或dataoutputstream时,代码运行良好,但当我使用printwriter或其他东西时,代码运行不好。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题