java - 套接字流

时间:2014-04-25 20:54:55

标签: java android eclipse sockets network-programming

我想从流中获取文字。但我没弄错。

一切都很好,但我只需要知道如何将PrintWriter变成字符串。

我尝试使用函数.ToString()转换PrintWriter,但它无法正常工作,是打印不同的字符串。

Java:

private ServerSocket Server_Socket;

private static final int CLIENTRPORT = 5000;

Socket socket = null;

class Connect_To_Client implements Runnable
 {
  @Override
  public void run()
   {
    try
     {
      Server_Socket = new ServerSocket(CLIENTRPORT);
      socket = Server_Socket.accept();
     }
    catch (IOException e)
     {
      e.printStackTrace();
     }
   }
}

public BufferedReader input;

public String Get_Message_From_Server()
 {   
  PrintWriter out = null;
  String out_string = "";

  try
   {
    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    System.out.println(input);
   }
  catch (IOException e)
   {
   e.printStackTrace();
   }
  return(out_string);//the text - problem
 }

1 个答案:

答案 0 :(得分:1)

要从缓冲的阅读器中读取类似的内容

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
       sb.append(line);
       line = reader.readLine();
}
return sb.toString();