2

This is my client code (J2ME):

SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:4444");
sc.openOutputStream().write("test".getBytes());
sc.close();

And this is my server code (J2SE):

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
OutputStream os = clientSocket.getOutputStream();

How would I go about creating a string representation of os?

1 Answer 1

7

InputStream and OutputStream are for byte sequences. Reader and Writer are for character sequences, like Strings.

To turn an OutputStream into a Writer, do new OutputStreamWriter(outputStream), or much better, use new OutputStreamWriter(outputStream, Charset) to specify a Charset, which describes a way of converting between characters and bytes.

(The other direction, InputStreamReader, is similar.)

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure I understand. Do you mean I should create an OutputStreamWriter using the OutputStream I get from clientSocket? If so, what do I do with it? How to I get the content of the output stream?
You don't "get contents of an output stream." You get contents of an input stream. That's...why it's called input. (In which case you'll probably want an InputStreamReader, not an OutputStreamWriter.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.