【发布时间】: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