【发布时间】:2012-06-09 16:45:30
【问题描述】:
在我有ServerSocket 监听传入连接的类中,代码如下:
while(isRunning)
{
try
{
Socket s = mysocketserver.accept();
acknowledgeClient(s);
new ClientHandler(s).start(); //Start new thread to serve the client, and get back to accept new connections.
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
下面是acknowledgeClient(Socket s)代码。
ObjectInputStream in = new ObjectInputStream(s.getInputStream);
ObjectOutputStream out = new ObjectOutputStream(s.getOutStream);
String msg = in.readObject().toString();
System.out.println(msg+" is Connected"); //Show who's connected
out.writeObject("success"); //Respond with success.
in.close();
out.close();
ClientHandler 的run() 方法。
try
{
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputstream(client.getOutputStream());
String msg = "";
while(!msg.equalsIgnoreCase("bye"))
{
msg = in.readObject().toString();
System.out.println("Client Says - "+msg);
out.writeObject("success");
}
in.close();
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
以下是客户端程序与此 Echo Server 通信的方式。
try
{
int count = 10;
client = new Socket("localhost",8666);
in = new ObjectInputStream(client.getInputStream());
out = new ObjectOutputstream(client.getOutputStream());
out.writeObject("Foo");
System.out.println("Connection Status : "+in.readObject().toString());
while(count>0)
{
out.writeObject("Hello!");
String resp = in.readObject().toString(); //Getting EOFException here.
System.out.println("Sent with :"+resp);
count--;
Thread.sleep(1000);
}
out.close();
in.close();
client.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
您可能已经注意到,在连接后确认客户端后,我关闭读/写流,并从为客户端提供服务的新线程中再次打开流,并从服务器读取/从连接的套接字开始写入,但是一旦我尝试读取服务器对客户端发送Hello! 的响应,它就会崩溃并以EOFException 而不是获得success。
我知道 EOF 发生的原因,但不知道为什么会在这里发生,我没有尝试读取其流中没有任何内容的套接字(它应该有 success 由服务器编写)。
客户端在服务器端打印Hello! 并写入success 作为响应之前尝试读取套接字是否为时过早?
附注: 我知道通过放置这么多代码来提问不是一个好方法,我们希望在这里得到问题的答案并理解它,而不是让别人解决我们的问题然后逃脱。所以,我提供了这么多代码来展示问题的各个方面。
【问题讨论】: