2

我已经连接到一个已经存在的服务器,其中包含我需要读取的字符串行。鉴于我只需要读取 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");}
}


  }
}

我知道这是一个非常基本的问题,我只是难以开始,仅此而已。我感谢任何澄清。谢谢。

4

2 回答 2

1

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

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

Then:
while(true){
    try{
        input.readLine();//Read from server
    }
于 2013-04-21T04:08:57.293 回答
0

在您的 while 之前添加以下行

 BufferedReader inp2 = new BufferedReader(new InputStreamReader(inp));
 while (true) {
    try {  
       inp2.readLine();
    }
 }
于 2013-04-21T03:57:11.013 回答