Stream is closed in java - java

This is the code I have
try
{
reader.read(msg1,0,6);
} catch (SocketTimeoutException e1){
loopcount = 1 ;
reader.close();
writer.close();
client.close();
reader = null;
writer = null;
client = null;
}
try
{
msg2 = new char[2000];
reader.read(msg2,0,intArrLen);
}catch (SocketTimeoutException e1){
loopcount = 1 ;
reader.close();
writer.close();
client.close();
reader = null;
writer = null;
client = null;
}
Inside the method, at this line reader. read (msg1,0,6) able to read the response correctly. After this when trying to read the response at the line reader. read (msg2,0,intArrLen).
It is giving stream is closed exception - Exception: java. I o. IO Exception: Stream closed. So need help in understanding why this exception is coming.

Firstly you are closing the connection of the reader and then without creating a new one calling the function using same reader which is close.
Instead, you can use reader.flush() method .
For more information please refer to the link.

Related

Two outputstreams?

I have the following code where I'm trying to create two different types of outputstreams. This doesn't seem to work. What would be the correct way to create two outputstreams? Specifically, one dataoutputstream and one objectoutputstream?
connect();
try (DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream())) {
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
outputStream.writeUTF("saveFile");
outputStream.writeUTF(serverName);
File fileToSave = new File(localName);
byte[] fileContent = Files.readAllBytes(fileToSave.toPath());
objectOutputStream.writeObject(fileContent);
return true;
}
} catch (IOException e) {
return false;
} finally {
disconnect();
}
After doing some debugging it seems just like the outputstream isn't working. If I only have one of the two, the two "writeUTF" statements will execute.
If I keep both of the outputstreams, the message never reaches the server.
The solution was to move the two "writeUTF" statements above the second try block.
connect();
try (DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream())) {
outputStream.writeUTF("saveFile");
outputStream.writeUTF(serverName);
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
File fileToSave = new File(localName);
byte[] fileContent = Files.readAllBytes(fileToSave.toPath());
objectOutputStream.writeObject(fileContent);
return true;
}
} catch (IOException e) {
return false;
} finally {
disconnect();
}
Now the code executes properly.
The problem with your code is that new ObjectOutputStream(...) writes a header to the stream, and evidently your reading code isn't symmetrical with this code, i.e. it does the readUTF() steps before constructing the ObjectInputStream, so the header isn't consumed yet, so the readUTF() steps see it, and barf.
The solution is that you don't need to do this at all. The DataOutputStream is completely pointless here. ObjectOutputStream has all the methods of DatataOutputStream, and more, and similarly for the input streams.
In general this kind of thing is not possible when one or more of the streams is buffered, as ObjectInputStream is.

Keep getting cast exception error when I'm reading a data file? [duplicate]

This question already has answers here:
Why does writeObject throw java.io.NotSerializableException and how do I fix it?
(4 answers)
Closed 7 years ago.
So I'm trying to write and read a data file and declare a new variable of type 'GroceryStore' after I read the data file. I keep getting cast exception errors when I'm running my program. Could someone explain to me why this is happening and how I can fix it? Thanks.
Here's my write data file method:
{
FileOutputStream file = null;
ObjectOutputStream outStream = null;
file = new FileOutputStream(new File(filename));
outStream = new ObjectOutputStream(file);
outStream.writeObject(store1);
System.out.print(filename + " was written\n");
}
Here's my read data file method
{
FileInputStream file = null;
ObjectInputStream inStream = null;
file = new FileInputStream(new File(filename));
inStream = new ObjectInputStream(file);
GroceryStore newStore = (GroceryStore) inStream.readObject();
store1 = newStore;
System.out.print(filename + " was read\n");
}
At first glance at the code for reading it seems to want to put it to fast to the class GroseryStore, probably need some parsing before you can get it in there. Try to System.out.println the input from the reader, then you know what you have, then parse / chop and slice that into what you need / want of it.
So, second make a class for the read / write operations. As an example of how the write might work for simple text output file you could use something like this:
private String file_name = "FileName";
private String file_extention = ".txt";
BufferedWriter writer = null;
public void writeTextToFile(String stuff_to_file) {
// trying to write (and read) is a bit hazardous. So, try, catch and finally
try {
File file = new File(file_name + file_extention);
FileOutputStream mFileOutputStream = new FileOutputStream(file);
OutputStreamWriter mOutputStreamWriter = new OutputStreamWriter(mFileOutputStream);
writer = new BufferedWriter(mOutputStreamWriter);
writer.write(stuff_to_file); // and finally we do write to file
// This will output the full path where the file will be written to.
System.out.println("\nFile made, can be found at: " + file.getCanonicalPath());
} catch (Exception e) { // if something went wrong we like to know it.
e.printStackTrace();
System.out.println("Problem with file writing: " + e);
} finally {
try { // Close the writer regardless of what happens...
writer.close();
} catch (Exception e) { // yes, even this can go wrong
e.printStackTrace();
} // close try / catch
} // close finally
} // close method

Problems with socket outputstream and inputstream

I'm trying to develop client-server connection between phone and pc using sockets. During the developing i met a problem and cannnot fix it yet. The problem is with outputstream. I use an ObjectoutputStream to send a String array to client and it works when I use this code:
try
{
// отправка пакета с файлами
DataInputStream dir = new DataInputStream(conn.getInputStream());
OutputStream dos = conn.getOutputStream();
ObjectOutputStream objectOutput = new ObjectOutputStream(dos);
byte messageType = dir.readByte();
switch(messageType) {
case 1:
try {
textArea.append("\nClient sends a command: " + dir.readUTF());
objectOutput.writeObject(results);
objectOutput.close();
} catch(Exception e) {
e.printStackTrace();
}
}
dir.close();
} catch (IOException e) {
......
but when I move ObjectOutputStream to the switcher:
try
{
// отправка пакета с файлами
DataInputStream dir = new DataInputStream(conn.getInputStream());
OutputStream dos = conn.getOutputStream();
byte messageType = dir.readByte();
switch(messageType) {
case 1:
try {
ObjectOutputStream objectOutput = new ObjectOutputStream(dos);
textArea.append("\nClient sends a command: " + dir.readUTF());
objectOutput.writeObject(results);
objectOutput.close();
} catch(Exception e) {
e.printStackTrace();
}
}
dir.close();
} catch (IOException e) {
....
my program freezes. I need to do like this, because i also need to do another commands, like sending and receiving files. Any solutions for this problem?
I've solved a problem. I just use BufferedReader & Writer for it, because it will be also used for transferring files.
So now code works fine and looks like this:
// отправка пакета с файлами
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), ENCODING));
String messageType = br.readLine();
switch(messageType) {
case "connect": {
List<String> results = new ArrayList<String>();
File[] files = new File("C:/Tenzor_Denis/ServerFiles/").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.toString().endsWith(".txt")) {
results.add(file.getName());
}
}
try {
for(int i = 0; i < results.size(); i++) {
bw.write(results.get(i));
bw.newLine();
//textArea.append(" " + results.get(i));
}
textArea.append("\nClient sends a command: " + messageType);
} catch(Exception e) {
e.printStackTrace();
}
bw.close();
br.close();
}
break;
}
}
Thx to all for answers.
Which line does it freeze on? It seems like reading from the input stream causes the output stream to block until everything is consumed. Look at the documentation for your conn object. What class is this? Perhaps moving the dir.readUTF() call before creating the ObjectOutputStream might solve it.
You can't do it either way. Closing the ObjectOutputStream will close the socket. You need to keep it open for the life of the socket. So moving it inside the case is futile anyway.
But your code doesn't make sense. You're writing with ObjectOutputStream, yet all you're reading from the peer is a single byte. If you're writing objects, you need to read objects, with an ObjectInputStream, not a DataInputStream, and when using both object input and output streams you must always construct the ObjectOutputStream first, at both ends to be safe.

Array of Sockets Java

I'm creating server and client java applications. I would like to create an array to store my sockets in. I'm using eclipse, and when I type in this line:
Socket[] sockets = new Socket[3];
Eclipse gives me an error saying "The resource type Socket[] does not implement java.lang.AutoCloseable".
How can I fix this?
Thank you
Try/Catch Statement:
try (
Socket[] sockets = new Socket[3]; //Line giving me error
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(ip));
Socket clientSocket = serverSocket.accept();
ServerClient client = new ServerClient(clientSocket);
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
//User input
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ port + " or listening for a connection");
System.out.println(e.getMessage());
continue;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
While Socket class itself implements AutoCloseable interface, array of Sockets - does not.
To put it in simple terms: you cannot open or close an array.
The resources defined in a try-with-resources block must all be auto-closeable. That's what it's for. Socket[] is not AutoCloseable, so it cannot be defined there. Move the declaration before the try. Ditto for any other resources you get the error on. Don't treat it as a general declaration block. It isn't.
When I run your code I recevie this error message
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: try-with-resources not applicable to variable type
(java.net.Socket[] cannot be converted to java.lang.AutoCloseable)
I advice you not to use try catch block with resources when you want to define your socket array.
try (
your rest of code
) {
define your array here ---> Socket[] sockets = new Socket[3];
String inputLine;
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
}
} catch (IOException e) {
your rest of code
Note: Socket class implements Closeable and AutoCloseable , yet array cannot be defined in try block like you tried to do
You can outsmart this problem easily, just create a class containing a socket connection, then build an array of this class object.
Build the class:
Class example
{
Socket con;
The constructor and extra code here
...
}
Then just build the array:
example[] arr=new example[3];

EOFException while using readObject() method in java

I am trying to read a message from the server. following is the piece of code:
try{
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
stdIn = new BufferedReader(
new InputStreamReader(System.in));
J = new JChatComm(out , in,"client","server");
String userInput = "Free for a chat?";
JPacket p = new JPacket(userInput,"client");
out.writeObject(p);
p = (JPacket)in.readObject();
if (!p.message.equals("Sure. Let us begin.")){
System.out.println("Server seems to be unavailable.");
socket.close();
}
else{
System.out.println("Chat Initiated..");
}
}
catch(Exception e){
e.printStackTrace();
}
But it gives the following output:
java.io.EOFException
at
java.io.ObjectInp utStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2596)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1317)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at JClient.callServer(JClient.java:35)
at jtalkG24.main(jtalkG24.java:18)
Line 35 is the line which has the readObject() method.
I am unable to figure out where I am going wrong.
You aren't going wrong. You've reached the end of the stream. That's what the exception means. You have to catch it and react accordingly.

Categories

Resources