ObjectOutputStream and PrintWriter Conflict - java

I have server and client set up, which is basically a basic text email system. I am currently using a PrintWriter to send the text between the server and client. I am trying to create a attachment based system and to do this I am using a ObjectOutputStream.
private static PrintWriter output;
private static ObjectOutputStream outStream;
public ClientHandler(Socket socket) throws IOException
{
client = socket;
outStream = new ObjectOutputStream(client.getOutputStream());
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
I currently have the problem where if I try send text via the output printwriter, for some reason extra characters will be added to the beginning of the text that is sent, meaning the program cannot identify key words being passed via the printwriter to the client. The problem will stop if i comment out the creation of the outStream object.
Can anyone give me any advice to try solve this problem of conflict?

This extra text is coming from the object output stream.
Attaching an ObjectOutputStream AND a PrintStream to the same outputstream is basically just never going to work. You have to come up with a solution for using 1 or the other. To use just a PrintStream, you might consider converting your object(s) to JSON or XML. On the other hand, you could just use an ObjectOutputStream and write your strings to the ObjectOutputStream

ObjectOutputStream should only be used as an ObjectOutputStream on that channel. Use the PrintWriter on another socket if you really need it.

Extend your ClientHandler and overwrite the constructor to include code for handling file transfers. Have two ports open, one for text and another for file transfers.
private static PrintWriter output;
public ClientHandler(Socket socket) throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
private static ObjectOutputStream outStream;
public ClientFileHandler(Socket socket) extends ClientHandler throws IOException
{
client = socket;
outStream = new ObjectOutputStream(client.getOutputStream());
}

Related

How can I read asynchronously from an inputstream?

I have a Socket with its input ad output stream. I want to use output synchronously and input asynchronously and store everything received without blocking the input.
Socket socket;
BufferedOutputStream outToServer;
DataInputStream inFromServer;
List<byte[]> incoming=ArrayList<byte[]>();
socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1",9100), 5000);
outToServer = new BufferedOutputStream(socket.getOutputStream());
inFromServer = new DataInputStream(socket.getInputStream());
How can I add an input listener to fill incoming list with incoming data?
Basically you want to look into the java.nio packages. There is full support for doing "async", "non-blocking IO" with standard java ... since quite some years.
See here for some examples. That tutorial basically starts with code as you have written in your question ... to transform that into "async".
But to be precise: you don't need to use "nio" or "nio2"; but if you are serious about turning into that direction, then nio/nio2 provide extremely helpful features.
There is no way to read InputStream asynchronously. You have to go where this InputStream is created, and access the source of data explicetly.
You need only to pass the InputStream to the Runnable that need to be executed asynchronously. This can be done for example in the constructor.
public class ConsumeInput implements Runnable {
private InputStream inputStream;
public ConsumInput(InputStream inputStream) {
this.inputStream = inputStream;
}
public void run() {
// Do something with inputStream
}
}
And in the main thread
...
ConsumeInput consumeInput = new ConsumeInput(inFromServer);
Thread t = new Thread(consumeInput);
t.start();
Obviously you can also use the new api to handle threads.
Note: this is only a skeleton code. You need to handle exceptions and closure of streams.

OutputSteam is abstract

as the title says, getting the error "outputsteam is abstract". I'm new to Java so not quite sure how to go about solving it. My program is trying to send an arraylist of connections over a socket to a client, using this code;
public void sendList(Socket clientSocket, ArrayList connections) throws IOException
{
OutputStream outputStream = new OutputStream(clientSocket.getOutputStream(), true);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(connections);
System.out.println("List sent");
}
Thanks in advance!
The error message is telling you exactly what is wrong: You can't call a constructor on an abstract class, and instead will have to initiate one of the concrete subclasses of OutputStream. Perhaps a BufferedOutputStream that wraps your clientSocket OutputStream.
Why do you even have this line?
OutputStream outputStream = new OutputStream(clientSocket.getOutputStream(),
true);
Why not simply use directly use the OutputStream from the clientSocket?

How to handle sending multiple messages over a socket connection?

I'm a bit of a beginner programmer so it's possible this is quite obvious and I'm overlooking the answer. But on to the question.
I have a two-part program (its a little more complicated than this example, but the situation is the same). The program has multiple messages fired between the client and the server. I have a PrintWriter on the server-side to send messages to the client, and on the client, I have a BufferedReader to read the messages sent.
When this example is run, I'm given two lines as output. The first message is both messages, and the second is NULL. What I am wondering is if there is a way to basically halt the server until I am ready for the second message, so that I can do something on the client-side before the second message is sent.
I am hoping to not use Thread.Sleep, as I would rather the Server wait around until the Client says it is ready.
This is the client:
public class Client{
public void run(){
Socket socket = null;
InputStream in = null;
BufferedReader reader = null;
try{
socket = new socket("LocalHost",1234);
in = socket.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
}
String messageFromServer = "";
try{
messageFromServer=reader.readLine();
}
System.out.println(messageFromServer);
String messageFromServer = "";
try{
messageFromServer=reader.readLine();
}
System.out.println(messagefromServer);
//close everything
}
}
This is the server:
public class Server{
public void run(){
ServerSocket server = null;
Socket client = null;
try{
server = new ServerSocket(1234);
client = server.accept();
}
PrintWriter writer = null;
OutputStream out = null;
try{
out = client.getOutputStream();
writer = new PrintWriter(out, true);
}
writer.write("Hi I'm a server");
//do some stuff that takes some time, user input, etc. etc.
writer.write("I'm still a server");
//close everything
}
Thanks :)
The problem with the way you currently have you code is the fact that you are using a BufferedReader, but the server is not terminating it's messages with a new line.
When you close the writer, the client is reaching the EOF or EOS and unblocking the read so it appears that both strings are being sent at once...
If you do something like...
writer.write("Hi I'm a server\n");
// This will force the message to be written to the client and picked up ;)
writer.flush();
writer.write("I'm still a server\n");
writer.flush();
Then you will get the messages seperatly...
You can use ObjectInputStream to read Objects instead of Strings.
This way you will read only one Message(String in your case) every call to ObjectInputStream.readObject();
BTW you can read the first message, "do something" and then read the second message. you don't have to read all of the sent messages at once.
If there are no other messages, then your thread will be blocked when trying to read an object from the ObjectInputStream.
Use it like:
ObjectInputStream inputStream = new ObjectInputStream( socket.getInputStream() )

Can't use InputStream from Socket after writeObject

Here is the situation:
I have a ServerSocket ss, and "Socket socket = ss.accept();", then if I do this:
istream = socket.getInputStream();
ostream = socket.getOutputStream();
in = new BufferedReader(new InputStreamReader(istream));
out = new PrintWriter(new BufferedOutputStream(ostream));
/*
I use in/out few times
everything OK
*/
ObjectOutputStream oos = new ObjectOutputStream(ostream);
oos.writeObject(someobject);
/* probably code that solves the problem */
String line = in.readLine();
On the client side I have this code:
PrintWriter out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
/*
using in/out, no problems
*/
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
SomeObject so = (SomeObject)ois.readObject();
out.println("some text");
Everything is OK, until I send someobject. Client recieves object properly, no problems there. But I can't use socket anymore. If I do oos.close(), I get Exception that says "socket closed". If I do oos.reset() I get Exception with similar message. "socket reset". So what should I do? Is it possible to use same input and output streams after writeObject()?
What happens when I send "some text" is that I'm just getting nulls no matter how many times I call readLine(), I never get that "some text".
You can't use multiple type of stream/reader/writer on the same underlying socket. All your streams and readers and writers are buffered so they will all get thoroughly mixed up. Stick tone kind. Stick to one protocol. If you have object streams, use them for everything. And create them once for the life of the socket, not per message.

Java readline() keeping socket open

I am trying to have my client connect to my server, and depending on the command send some string back to the client. Currently the app connects and can send strings to the server very nicely. However when I send the command which instructs the server to send something back it hangs. I found that the problem occurs when the client attempts to read the line send from the server.
Server
PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
out.println("GETDATA" + "\n");
out.flush();
out.close();
Client
BufferedReader fromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
incomingLine = fromServer.readLine();
Log.d("HERE", "NOT " + incomingLine);
fromServer.close();
Thanks!
I made effectively this same mistake when I was first doing sockets as well.
Don't use PrintWriter with BufferedReader. They're incompatible. By comments, PrintWriter actually hides critical exceptions, so they shouldn't be used in networking. Instead, use a DataInputStream and DataOutputStream for communications.
client = new Socket(hostname, port);
inStr = new DataInputStream(client.getInputStream());
outStr = new DataOutputStream(client.getOutputStream());
Then, send and receive using writeUTF and readUTF, like so:
public void send(String data) throws IOException {
outStr.writeUTF(data); outStr.flush();
}
public String recv() throws IOException {return inStr.readUTF();}
The reason has to do with the UTF encoding; a BufferedReader expects a certain string encoding, which PrintWriter does not give. Thus, the read/write hangs.
The method readLine() expects an end of line character "\n" maybe that's your problem

Categories

Resources