如何读取服务器的输入行? (java客户端控制台应用)

时间:2013-04-21 03:53:00

标签: java sockets client inputstream

我已经连接到一个已经存在的服务器,其中包含我需要读入的字符串行。鉴于我只需要读取一个String类型,哪个输入阅读器可以在这里工作,所以我可以在我的行中逐行读取循环?这是我的简单客户端:

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");}
}


  }
}

我知道这是一个非常基本的问题,我只是难以入门,就是这样。我感谢任何澄清。感谢。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

在您的

之前添加以下行
 BufferedReader inp2 = new BufferedReader(new InputStreamReader(inp));
 while (true) {
    try {  
       inp2.readLine();
    }
 }
相关问题