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.
Related
This question already has answers here:
Java - Understanding PrintWriter and need for flush
(2 answers)
Closed 6 years ago.
I am trying to make a simple quiz between client and server. The server sends an array of questions and waits for a reply from client. The problem is that the client side does not display the array from server nor can take any input. The server has definitely connected to the client, but the client side stays idle.
Server:
OutputStream o =sock.getOutputStream();
PrintWriter pw = new PrintWriter(o);
InputStream is = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
int i=0;
while(i<10)
{
pw.println(array[i]);
String st = br.readLine();
System.out.println(st);
i++;
}
Client:
InputStream istream = sock.getInputStream();
BufferedReader content = new BufferedReader(new InputStreamReader(istream));
String str;
OutputStream ostream=sock.getOutputStream();
PrintWriter pw = new PrintWriter(ostream)
String ans;
for(int j=0;j<10;j++)
{
str=content.readLine();
System.out.println(str);
ans=sc.nextLine();
pw.println(ans);
}
PrintWriter#println doesn't flush text to client by default so you need to call pw.flush() manually each time you want to ensure sending.
To let println automatically flush text to client use PrintWriter(Writer out, boolean autoFlush) constructor with autoFlush parameter set as true, like
PrintWriter pw = new PrintWriter(o, true);
since PrintWriter(OutputStream out) constructor internally invokes this(out, false); so automatic flash is disabled println, printf or format methods.
PrintWriter doesn't flush information itself by default.
You should either add: pw.flush() after pw.println(ans) or create your writer in that way: PrintWriter pw = new PrintWriter(o, true);
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));
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.
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();
I'm trying to communicate between 2 programs in Java with Java Sockets. I want to send some bytes through the socket as Data. Those bytes being data, their value can be anything (so could be 0 and possibly -1). I tried to use the DataInputStream class to handle the communications and works fine if i don't receive the byte 0 somewhere in the bytes i am trying to read, otherwise, it seems to block at this 0 byte and stop reading. Any one would have any ideas on the how or why this is happening and any ideas on how to work this around ? Thanks !
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");