like the headline says I´m getting an EOFException on the serverside after i called shutdownOutput() at the clientside
this is at the serverside:
public void getRestaurant() {
String tempRestaurant=null;
try { BufferedReader fr =
new BufferedReader( new FileReader( "Restaurant.txt" ));
tempRestaurant = fr.readLine();
System.out.println( tempRestaurant );
System.out.println("writing tempRestaurant is the next Step");
oos.writeObject(tempRestaurant);
System.out.println("tempRestaurant has been written");
oos.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
and this is the code at the clientside:
protected String doInBackground(Void... params) {
connecttoServer();
System.out.println("connecting to server...");
try {
oos.writeInt(1);
System.out.println("next step is closing");
serverside.shutdownOutput();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("connected to server");
Restaurant=(String) ois.readObject();
System.out.println("doInBackground(): "+Restaurant);
and this is the error code:
java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at prealphaserverpackage.clientsidethreads.handlerequest(Serverpart.java:355)
at prealphaserverpackage.clientsidethreads.run(Serverpart.java:156)
pls comment if you need any further informations i will put them online as soon as possible :)
I forgot to call oos.flush(); While the server was still waiting for the data, I closed the stream. That was the reason for the EOFException.
Related
I'm from Poland, so I'm sorry for any mistakes.
I've coding for a while a small server and client connection, when I stopped on annoying problem. When I send from client to server information (String), server can get it, but can't respone to it.
Here it is code.
Client
private static Socket socket;
public static void main(String args[]){
try{
String host = "localhost";
int port = 25002;
InetAddress address = InetAddress.getByName(host);
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 5000);
//Send the message to the server
System.out.println("< "+sendMessage(socket));
//socket.shutdownOutput();
System.out.println("> "+getMessage(socket));
}catch (SocketTimeoutException e){
System.out.println(e.getMessage()); // changed
}catch (IOException e){
System.out.println(e.getMessage()); // changed
}catch (IllegalBlockingModeException e){
System.out.println(e.getMessage()); // changed
}catch(IllegalArgumentException e){
System.out.println(e.getMessage()); // changed
}finally{
//Closing the socket
try{
socket.close();
}catch(Exception e){
System.out.println(e.getMessage()); // changed
}
}
}
public static String sendMessage(Socket client){
try {
String message = "test";
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer = new PrintWriter(client.getOutputStream(), true);
writer.print(message);
writer.flush();
writer.close();
return message;
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
return "false";
}
}
public static String getMessage(Socket client){
try {
BufferedReader socketReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
return socketReader.readLine();
} catch (IOException e){
System.out.println(e.getMessage()); // changed
return "false";
}
}
And.. server
public class kRcon{
private static Socket socket;
private static ServerSocket serverSocket;
private static Thread u;
private static class Server extends Thread {
public void run() {
int port = 25002;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while(true) {
try {
socket = serverSocket.accept();
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter socketWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String str = socketReader.readLine();
socketReader.close();
System.out.println(str);
socketWriter.write("test");
socketWriter.flush();
socketWriter.close();
}
}catch (IOException e1) {
e1.printStackTrace();
}
}
public static void init(){
try {
u = new Server();
u.setName("Server");
u.start();
} catch (IOException e) {
System.out.println(e.getMessage()); // changed
}
}
}
Results
If, I start server first all looks nice.
So, I start the client with parametr "test", nad output to console is:
< test
Socket is closed // changed
On server-side in console I have:
"test"
Socket is closed // changed
I tried to shutdown inputs and outputs and dosen't work.. I don't know to do now. Please help :c
Edited 2015-04-03
I've changed lines with comment "changed".
For Google, and readers
To fix problem, don't close StreamReaders nad StreamWriters on client's sides.
Thanks to EJP, for help!
Greetings from Poland.
When you get an exception, print it. Don't just throw away all that information. And don't return magic Strings either. In this case you should have let the exception propagate. If you had done all that you would have seen the exception SocketException: socket closed being thrown by getMessage(), and you would have had something concrete to investigate, instead of a complete mystery.
It is caused by closing the PrintWriter in sendMessage(). Closing either the input or output stream of a socket closes the other stream and the socket.
I'm rather new to server sockets, trying to learn how to code a socket (ive had past experience with using sockets like winsock but this is my first time actually coding one in java).
This is the error I keep getting:
Couldn't get I/O for the connection to: 0
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
This is the code:
public static void main(String args[]) {
ServerSocket MyService = null;
Socket clientSocket = null;
Integer clientNum = 0;
Integer inputID, outputID;
try {
MyService = new ServerSocket(hidden);
} catch (IOException e) {
e.printStackTrace();
}
try {
clientSocket = MyService.accept();
ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
Float inputFloat = null;
Float outputFloat = null;
Protocol protocol = new Protocol();
outputFloat = protocol.processFloatInput(null);
while(true) {
if(input.readObject().getClass().equals(inputFloat.getClass())) {
System.out.println("true");
if ((inputFloat = input.readFloat()) != null) {
outputFloat = protocol.processFloatInput(inputFloat);
output.writeObject(outputFloat);
System.out.println("Float value = " + inputFloat);
}
input.close();
output.flush();
output.close();
}
if(input.readObject().getClass().equals(Integer.TYPE)) {
if ((inputID = input.readInt()) != null) {
outputID = protocol.processIntegerInput(inputID);
output.writeObject(inputID);
System.out.println("Client " + outputID + " connected.");
}
input.close();
output.flush();
output.close();
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
//Error printed
System.err.println("Couldn't get I/O for the connection to: " + clientNum);
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
};
In past tests, i was able to connect to the server, but since I want to check the input data type before operating, I get this.
Thanks for the help :)
EOFException just means you got to the end of the stream. It's normal.
Your problem is that you're reading twice for every object written: once to get its class and again to get the object. You don't get the same object again, you get the next object, so you run out eventually.
You need to store the result of readObject() in a variable, then test its class, then cast it appropriately.
I'm trying to send a string to the servlet from java program and retrieve the same string with some padding.
Here's the code i'm working on and the problem is java.io.EOFException is being thrown at the establishment of inputstream in java program.
why does the end of stream is occuring when i'm setting it up. please clarify my doubt.
Servlet program is
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProgServlet implements Servlet {
public void init(ServletConfig sc){
}
public void service (ServletRequest req,ServletResponse res)
throws ServletException, java.io.IOException
{
}
public void destroy(){
}
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
//Setting up streams
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
String p = "Server String";
//Receiving data from client and resends by padding
try {
p = (String) ois.readObject();
p = p.concat(" -sever padding");
oos.writeObject(p);
oos.flush();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
}
}
java program on client is
public static void main(String arg[]) throws IOException{
System.out.println("Enter a string :");
Scanner s = new Scanner(System.in);
String data = s.next();
s.close();
URL serv = null;
try {
serv = new URL("http://10.0.0.9:8080/project/projectservlet");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection servletConnection = null;
System.out.println("establishing communication with server....");
try {
servletConnection = (HttpURLConnection) serv.openConnection();
System.out.println("connection with the server established"+servletConnection.getRequestMethod());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
servletConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(""+servletConnection.getRequestMethod());
servletConnection.setDoOutput(true);
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
System.out.println("setting up streams to communicate...");
ObjectOutputStream dos = null;
ObjectInputStream dis = null;
try {
dos = new ObjectOutputStream(servletConnection.getOutputStream());
System.out.println("Streams are up and ready to go");
System.out.println("Sending data to the server...");
dos.flush();
dos.writeObject(data);
dos.flush();
System.out.println("Data sent successfullyy \n Retrieving data from server");
dis = new ObjectInputStream(servletConnection.getInputStream());
data = (String) dis.readObject();
System.out.println("Data retrieved from the server is "+data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
dos.close();
dis.close();
servletConnection.disconnect();
}
}
the output and stack trace is
Enter a string :
jaggu
establishing communication with server....
connection with the server established
GET
POST
setting up streams to communicate...
Streams are up and ready to go
Sending data to the server...
Data sent successfully
Retrieving data from server
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ServletInvokation.main(ServletInvokation.java:57)
Exception in thread "main" java.lang.NullPointerException
at ServletInvokation.main(ServletInvokation.java:69)
In the java client, the output stream represents the request sent to the server, and the input stream represents the response retrieved from the server. When you call servletConnection.getInputStream(), you are requesting the response from the server, so it immediately sends the HTTP request to the server. But if you look at your code, at that point you have not yet written anything to the output stream, so you are actually trying to send an empty request, and that's why you are getting an EOFException.
Try doing it in two steps instead. First, get the output stream, write to it and close it. Then get the input stream and read from it.
See also this answer.
Close OutPutStream in servlet after servlet work is completed.
So I have this simple server. What I want to do is keep the server running and waiting for another client, when I kill the clients socket (telnet -> end process).
private ServerSocket serv;
public Server() throws IOException {
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
while(true) {
//do stuff
}
} finally {
sock.close();
}
}
} catch (SocketException e) {
recreateSocket();
} catch (IOException e) {
e.printStackTrace();
}
}
private void recreateSocket() {
try {
ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port);
serv = socket;
} catch (IOException e) {
e.printStackTrace();
}
}
Atm it throws bindException, how to deal with it.
Add catch statement(s) to before the finally block (but don't call recreateSocket() there )
Update to clarify, something like this:
while(true) {
//do stuff
}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
sock.close();
Start a new thread to handle each accepted connection.
The reason is that you are creating a server socket again. You don't need to do this (the previous one is still working which is why you get a bind exception). This is what you want to do:
private ServerSocket serv;
public Server(int port) throws IOException
{
try {
serv = new ServerSocket(port);
serv.setReuseAddress(true);
while(true) {
Socket sock = serv.accept();
try {
BufferedReader netIn = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter netOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sock.getOutputStream())), true);
// do stuff
} catch(SocketException e) {
e.printStackTrace();
} finally {
sock.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
I have seen a similar problem as mine but I still wasn't able to resolve this.I am trying to do a relay chat. I've done all the flushing. I even tried autoflush(with println). But after the first message I sent to server, succeeding messages aren't sent anymore. I am not closing the printwriter. I checked the socket and yes, it's still connected, I printed the message to be sent, nothing seems to be wrong. Help would be very much appreciated.
here is a part of the client code:
public void initializeConnection(){
try {
host = InetAddress.getLocalHost();
clientSocket = new Socket(host.getHostAddress(), port);
outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
String message = outMsgArea.getText()+"Hello";
outToServer.println(message);
System.out.println(clientSocket.isConnected());
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==quit){
try {
outToServer.close();
clientSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
else if(e.getSource()==button){
if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
/*try {
outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
String message = outMsgArea.getText()+"Hello";
System.out.println(clientSocket.isConnected());
outToServer.println(message);
outToServer.flush();
//outToServer.println(message);
outMsgArea.setText("");
}
}
}
server:
while(true) {
try {
Socket connectionSocket = servSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
String clientSentence = inFromClient.nextLine();
System.out.println(clientSentence);
}
catch(IOException ioEx) {
ioEx.printStackTrace();
}
}
}
I don't think
Socket connectionSocket = servSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
should be inside the while loop.