java - 如何从服务器读取输入行? (Java客户端控制台应用程序)

标签 java sockets client inputstream

我已连接到包含需要读入的字符串行的服务器,因为我只需要读入String类型,哪种输入阅读器将在这里工作,所以我可以在While循环中逐行阅读?这是我简单的客户:

public class Client
{
public static final int PORT_NUMBER = 8888;


public static void main(String[] args)
{
 int port = PORT_NUMBER;
 String content;
 OutputStream output;
 InputStream input;
 Socket s = null;

try
{
 s = new Socket("server.example.exp", port);
 output = s.getOutputStream();
 input = s.getInputStream();

 System.out.println("Connected to " + s.getInetAddress() + " on port " + s.getPort());
}
catch (IOException e) {System.err.println(e);}

while (true)
{
 try
 {
  //read next line from server
 }
 catch (EOFException eof){
  System.out.println("eof encountered" + eof.getMessage());
  break;
 }
 catch (OptionalDataException ode){System.out.println("OptionalDataException" + ode.getMessage());}
 catch (IOException ioe){System.out.println("IOException on read object");}
 catch (ClassNotFoundException cnf){System.out.println("ClassNotFoundException");}
}


  }
}

我知道这是一个非常基本的问题,仅在入门方面遇到困难,仅此而已。我感谢您的澄清。谢谢。

最佳答案

要从InputStream读取,可以将其包装在InputStreamReader中,然后在BufferedReader中,您可以从中读取Line:

BufferedReader input;
input = new BufferedReader(new InputStreamReader(s.getInputStream()));

Then:
while(true){
    try{
        input.readLine();//Read from server
    }

关于java - 如何从服务器读取输入行? (Java客户端控制台应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127793/

相关文章:

java - 线程中出现异常 "Thread-0"java.lang.NullPointerException

c++ - 从一组套接字中检测超时套接字

c - c语言客户端向http服务器发送文件

c# - 爱普生 ESC/POS 命令 DLE EOT n 没有返回响应

java - 针对蜂窝调制解调器项目的客户端/服务器交互故障排除的建议和帮助

java - 快速Java链表问题

java - @Secured 和@PreAuthorize 注解在哪些方法中起作用?

java - 如何编译 JShop2 src

Java socket.io 客户端 portage

Java Generic Map 未在运行时转换为正确的类型以进行 Json 转换