Java socket reading issue when receives 0 - java

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");

Related

BufferReader stucks when using read()

I have developed a small java client that suppose to communicate with a tool installed on unix-server.
I'm working with Socket first time so could do something wrong. I am also limited to Java 6.
In brief code looks like this
I use Socket to establish connection.
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(endpoint, port);
socket.connect(socketAddress, 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Here is how I send message
out.println("Hello");
out.flush();
And here is how I read response
String res = "";
int letter;
while(letter = in.read() != -1) {
char c = (char) letter;
res += c;
}
F.x. If I send a message "Hello", I will receive answers with 2 lines (see example below)
> Hi there
> My name is Robot
The things stuck when I read next character after "Robot\n", I expected that in.read() != -1 will be true and thus it will stop itself, but that is not a case and instead everything just stuck.
What could be the reason to this and how to solve? Thanks.
Please let me know if I need to provide more information.
I had to close my output writer before reading from it, otherwise it blocks.
if (!socket.isOutputShutdown()) {
socket.shutdownOutput();
}
The answer came from a person who later deleted own answer :-/

Java socket: Can't send proper data

I have a Java TCP server, and an android TCP client. I'm trying to send data from client to server. Sending the data seems to be working fine, but the data that is sent, seems corrupted.
Socket connectionSocket = socket.accept();
BufferedReader inFromClient = new BufferedReader(new InputStreamReader( connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
System.out.println(clientSentence.split(":")[0]);
if(clientSentence.split(":")[0].equals("packet"))
{
When the server receives the data, the prints show something like this in the console:
packet:user:pass
packet
Which is as expected. But still my if isn't returning true. As if the "packet" string got from socket, is different from the one I type with keyboard in my source. I can't even copy the text from console. When I copy with mouse and paste it somewhere, it only copies the first character.
I use the same structures on client side and send the packet with [DataOutputStream].writeChars(message)
I don't know if it's a different coding of characters that cause this, or something else. Also it's worth noting that when i capture the text with wireshark, the string is something like ".p.a.c.k.e.t"
Thanks.
EDIT: As asked, client side code is something like this:
Socket clientSocket = new socket("127.0.0.1", 1234);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
String message = "packet:" + username + ":" + password + "\n";
outToServer.writeChars(message);
It's on an android device.

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.

Empty Socket InputStream

I'm trying to build a simple web server in Java as practice but I'm running into a very strange issue. When I attempt to read the InputStream from the Socket, sometimes there is no data to be read.
The process I'm following is this:
I create a ServerSocket, listening on port 80, and call accept() to get a Socket. I then send a request from my browser (Firefox) to localhost, which triggers the accept() to return the Socket.
Sometimes, it will read the HTTP request perfectly. Other times, it fails to read any data (read() returns a -1).
Here is some sample code to illustrate what I'm doing, without any exception handling thrown in:
ServerSocket serv = new ServerSocket(80);
while (true)
{
Socket con = ServerSocket.accept();
InputStream input = con.getInputStream();
bytes[] bytes = new bytes[4000000]; // for simplicity, I figured I'd
// just make the array huge for now
int bytesRead = input.read(bytes);
if (bytesRead > 0)
{
StringBuffer sBuffer = new StringBuffer(bytesRead);
for (int i = 0; i < bytesRead; i++)
{
sBuffer.append((char) bytes[i]);
}
System.out.println(sBuffer.toString());
}
}
EDIT: I've also tried using a BufferedInputStream and BufferedReader to not avail.
One socket can receive more packets. So you should create a new thread for every socket. Something like:
while(true){
Socket socket = serv.accept();
Client client = new Client(socket);
new Thread(client).start();
}
Then you need to create the Client class which implements the runable interface.
Socket socket;
public Client(Socket socket){
this.socket = socket;
}
public void run(){
while(socket.isConnected()){
//here reads the packets from the inputstream
}
}
You should always loop when reading data from an InputStream. there is no guarantee that all the data will be returned from a single read() call (loop until you receive -1).

Categories

Resources