在我有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崩溃而不是获得成功.
我知道EOF发生的原因,但没有弄清楚为什么会发生这种情况,我不是在尝试读取其流中没有任何内容的套接字(它应该由服务器编写成功).
在服务器打印Hello之前,客户端是否尝试读取套接字是否为时尚早!在结束和书面成功作为回应?
附: :我知道通过提供如此多的代码来问问题不是一个好方法,我们期望在这里获得问题的答案并理解它,而不是让我们的问题由其他人解决并逃脱.所以,我提供了这么多代码来展示问题的所有方面.