Write to DataOutputStream from Java and reading it on C# - java

I need to know how can I read input stream in C# from the following written bytes in Java:
// This is in the java client.
byte[] data = "some string".getBytes(Charset.forName("US-ASCII"));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(data.length);
out.write(data);
out.flush();
The reason I'm asking this it's cause of the writeInt(int) method which I don't now how does it alters the sent bytes.

I have written a C# Conversion of Java's DataInputStream and DataOutputStream you can collect them here.
https://bitbucket.org/CTucker1327/c-datastreams/src
To construct these classes you would pass a BinaryWriter or BinaryReader into the constructor.
To Construct DataOutputStream
DataOutputStream out = new DataOutputStream(new BinaryWriter(Stream));
To Construct DataInputStream
DataInptuStream in = new DataInputStream(new BinaryReader(Stream));

Related

BufferedReader readLine() have weird characeters

I have found a issue when I write and read data from sockets, in this time the socket are already open.
The code from server:
<pre>ServerSocket server = new ServerSocket(2001);
Socket socket = server.accept();
while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readString = br.readLine();
System.out.println("result:\n"+readString)
}</pre>
The test I made from a client
<pre>Socket socket = new Socket("localhost", 2001);
Scanner consoleRead= new Scanner(System.in);
consoleRead.useDelimiter("\n");
ObjectOutputStream oo = new ObjectOutputStream(socket.getOutputStream());
while(true){
String s = consoleRead.next();
oo.writeUTF(s+System.lineSeparator());
oo.flush();
}</pre>
The first line is read perfectly... But the rest begin with weird characters.
Regards
If you are writing with ObjectOutputStream then read with ObjectInputStream insted of InputStreamReader
writeUTF()
Primitive data write of this String in modified UTF-8 format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream.
Better is :- Write with OutputStreamWriter and read with InputStreamReader
For better understanding:- write the same thing in a file with ObjectOutputStream and then check what is getting written.

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 sockets and file Streaming

I have a basic question on files ... It seems that I am stuck.
I am creating a server-client socket. The client sends a random number of integers to the server using an iterative way and the methods bellow.
//BufferedWriter out = new BufferedWriter(new OutputStreamWriter (sock.getOutputStream()));
out.write(number);
out.flush();
The server accepts them like this:
//BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
number=in.read();
All , I want is the server to store all these integers into a file (myfile.txt for example) and then I want to read this file as a string (with all integers) in order to send it back to the client.
Any ideas? I tried few methods but right now I am totally stuck and I really cant think clear... I would really appreciate it if someone could help me out a bit.
Cheers
EDIT: I tried these methods so far
FileOutputStream fos = new FileOutputStream("myfile.txt");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(number);
And then I tried to read this with
FileInputStream fin=new FileInputStream("myfile.txt");
DataInputStream dis = new DataInputStream(fin);
int numbers = dis.read();
But all I get is the number 0. :S
Writing the file could be achieved like this
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
// Make sure to write the data as a String
bufferedWriter.write("" + number);
bufferedWriter.close();
fileOutputStream.close();
Afterwards, reading can be achieved like this
FileInputStream fileInputStream = new FileInputStream("test.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = bufferedReader.readLine();
number = Integer.valueOf(line);
Advantage of using a BufferedWriter and a BufferedReader is that you can read / write Strings and have a human readable file. Using a DataOutputStream, you'd have a binary file, and you'll have do conversion from / to your data format yourself.
Regarding your code example:
dis.read();
will return you the number of bytes read, not the actual data. You'd do that using
dis.readInt();

Receive file info using DataInputStream and write it

I am trying to receive a file that client sends using DataInputStream and write it into file.
(Client sends the file using DataInputStream write(byte[], len, off) method)
Here's how I am trying to do, but it does not receive full data.
InputStream in = s.getInputStream(); //s is Socket that is connected.
BufferedInputStream bis = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bis);
FileOutputStream fos = new FileOutputStream(directory+"/"+filename);
byte b = din.readByte();
while(b != -1){
fos.write(b);
b = din.readByte();
}
I know that the implementation above may not be elegant.
but I am really new to java so please forbear with me about bad style
(I really appreciate if you recommend better one if you know)
the result file is only 4KB whereas it should be 401KB
How should I fix this code so I can have my code working?
THank you very much.
you are reading a byte, and -1 (cast to a byte) is a valid byte value. you don't want to stop on -1, but should instead catch EOFException.
you test for -1 when using one of the standard InputStream.read() methods (which return int, not byte).

Can I change the type of stream I'm using without closing and reopening the socket in Java?

I'm doing some socket programming in Java and I'd like to be able to change between using the ObjectOutputStream, the DataOutputStream, and the PrintWriter all within the same socket/connection. Is this possible and what is the best way to do it?
I've tried just creating both types of objects, for example ObjectOutputStream and DataOutputStream, but that doesn't seem to work.
The reason I want to switch between them is to, for example, send a text command "INFO" that signals I'm about to send an object with information or a command "DATA" signalling that I'm about to send data. Any advice on the best way to do this is appreciated.
You can only use one underlying stream type however you can get that data from anywhere.
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
public static void writeObject(DataOutputStream dos, Serializable obj) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
oos.close();
dos.writeUTF("OBJECT");
byte[] bytes = baos.toByteArray();
dos.writeInt(bytes.length);
dos.write(bytes);
dos.flush();
}
public static void writeBytes(DataOutputStream dos, byte[] bytes) {
dos.writeUTF("BYTES");
dos.writeInt(bytes.length);
dos.write(bytes);
dos.flush();
}
public static void writeText(DataOutputStream dos, String text) {
dos.writeUTF("TEXT");
dos.writeUTF(text);
dos.flush();
}
Why do you want the *Stream to convert to the *Writer.
You can do what you want to do with *Stream.
Socket s = new Socket();
DataOutputStream stream = new DataOutputStream( s.getOutputStream() );
byte[] bytes = "INFO".getBytes();
stream.write(bytes);
//....
bytes = "DATA".getBytes();
stream.write(bytes);

Categories

Resources