【问题标题】:How to read lines of input from server? (java client console application)如何从服务器读取输入行? (Java 客户端控制台应用程序)
【发布时间】:2013-04-14 05:09:12
【问题描述】:

我已经连接到一个已经存在的服务器,该服务器包含我需要读入的字符串行。鉴于我只需要读入 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,尽管不能保证它在进入while循环时是有效的。那么你的问题是什么?
  • 对不起,我知道它目前缺乏验证。只是一个可以学习的骨架。我的问题是如何使用 InputStream 对象来读取NextLine?可用的方法——比如 read()——只返回 int。

标签: java sockets client inputstream


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在 while 之前添加以下行

     BufferedReader inp2 = new BufferedReader(new InputStreamReader(inp));
     while (true) {
        try {  
           inp2.readLine();
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多