gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:54:19 26 4
gpt4 key购买 nike

我已连接到包含需要读入的字符串行的服务器,因为我只需要读入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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com