BufferedReader readLine method hangs and block program - java

I'm trying to learn sockets using Java and I sucessfully sent data to a ServerSocket running in my own machine. When I try to read from this socket using readline (so I can just echo my own sent message) my program hangs and won't return.
Here's the code:
public static void main(String[] args) throws UnknownHostException, IOException {
TCPClient cli = new TCPClient("127.0.0.1", "15000");
try {
cli.ostream.writeUTF("Teste");
String echo = cli.istream.readLine(); //it hangs in this line
System.out.println(echo);
}
TCPClient is a class I defined so I can test my program on a simpler interface before using swing on my homwework. here's the code:
public class TCPClient {
public DataOutputStream ostream = null;
public BufferedReader istream = null;
public TCPClient(String host, String port) throws UnknownHostException {
InetAddress ip = InetAddress.getByName(host);
try {
Socket socket = new Socket(host, Integer.parseInt(port));
ostream = new DataOutputStream(socket.getOutputStream());
istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
My server is pretty simple. After the connection is estabilished, it enters in this loop and stays here until I close the client (because of the infinite loop). Afterwards, some exception handling returns it to the point before the connection started.
while(true){
String msg = istream.readLine();
System.out.println("Arrived on server: " + msg); //just works on debug
ostream.writeUTF("ACK: " + msg);
ostream.flush();
}
I don't see what am I missing.
PS: the wierd stuff is that if I debug the server, I can see the message arriving there (I can print it, for example), but this isn't possible if I just run this code. Does this have some concurrency relation I'm overlooking?
thx

The problem is that readLine tries reading a line. It will not return the line until it's sure that the end of line has been reached. This means that it expects either a newline character, or the end of the communication. Since the server doesn't send any newline char and doesn't close the stream, the client waits indefinitely.

cli.ostream.writeUTF("Teste");
Shouldn't this be containing a new line? Otherwise read method will be waiting for new line I think.
Also as suggested you can try flushing the ostream after writing to it.

writeUTF() doesn't write a line. See the Javadoc. writeUTF() is for use with readUTF(). And Readers are for use with Writers. So change the DataOutputStream to a BufferedWriter and call write() and then newline().

Related

Java - Server and Client not interacting (Socket)

I'm currently working on a small chat-program. The 2 classes, I have a problem with are the classes containing the clientside and the serverside of a socket. I want them to interact, sending a string from the server to the client, but the string isn't received apparently. I also don't get an error. Can someone explain, why this happens or how to fix it?
Codesnippet from the client:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true) {
System.out.println("WAITING");
System.out.println(br.readLine());
}
} catch(Exception ex) { ex.printStackTrace(); }
Codesnippet from the server:
// Method of the code throws Exception
System.out.println("Waiting for someone to connect.");
Socket socket = serverSocket.accept();
System.out.println("Someone connected.");
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os, true);
while(true) {
System.out.println("WRITING");
pw.write("hi");
}
The output is currently:
server:
WRITING
WRITING
WRITING
WRITING
WRITING
...
client:
WAITING //only once
The client expects a complete line:
br.readLine()
and blocks until the line is complete.
But the server only sends "hi" repeatedly, without ever sending any EOL character:
pw.write("hi");
So the line never ends, and the client keeps blocking.
Use pw.println("hi");
The server buffer is not getting flushed. If you change pw.write(...) to pw.println(...) it should fix the issue - println(...) auto-flushes the buffer

java client-server issue on client side (no System.out)

probably a noobish Q:
So i made a very simple single-threaded server/client model. Now when i execute the program in the eclipse IDE it shows me System.out's of the server and not the ones from the client.
When i press terminate, the System.out.println lines that were supposed to be generated by Client show up.
I'm struggling with this for days now.. Hopefully someone can help me out.
Thanks in advance!
SERVER:
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args)
{
new Server();
}
public Server()
{
try
{
ServerSocket serverSocket = new ServerSocket(8000); //nieuw instantie van een ServerSocket
System.out.println("Waiting for clients..");
Socket socket = serverSocket.accept(); // lister for socket requests
while(true)
{
BufferedReader inputClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream clientOutput = new DataOutputStream(socket.getOutputStream());
String clientInput = inputClient.readLine();
System.out.println("Server: clientInput= : " + clientInput);
InetAddress hostAddress = InetAddress.getByName(clientInput);
String iPaddress = hostAddress.getHostAddress();
System.out.println("Server: IP = : " + iPaddress);
clientOutput.writeBytes(iPaddress);
clientOutput.flush();
}
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
CLIENT:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
new Client();
}
public Client()
{
try
{
Socket socket = new Socket("localhost", 8000);
DataOutputStream toServer = new DataOutputStream(socket.getOutputStream());
BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
toServer.writeBytes("google.com" + '\n');
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
}
catch(IOException ex)
{
System.err.println(ex);
}
}
}
When you start a client and a server program, they will have 2 separate consoles. Only one is visible at a time in the "Console" view of Eclipse. That is why you only see the server's.
You can switch between the active consoles with the "Display Selected Console" icon (it's a monitor icon) and also see the active console list.
Also you have a full-duplex connection. Both the client and the server can read/write. You use a DataOutputStream - BufferedReader representation for a one-way communication which is WRONG.
DataOutputStream writes binary data, BufferedReader reads text (character) data.
You should use one of the following pairings:
DataOutputStream - DataInputStream and use writeUTF() and readUTF() methods
OR
PrintWriter - BufferedReader and use println() and readLine() methods
clientOutput.writeBytes(iPaddress);
clientOutput.write("\n".getBytes());
clientOutput.flush();
Just add these lines (second line) in your Server class.
Reason
In your Client class you are reading a line from buffer reader but you have not send any character from server indicating end of line. So in the second line we are writing new line character indicating end of line.
When you close the server, connection get reset and available input are read. Thats why your Client prints if you close the server.
Optionally if you only want to modify your Client class you can write these lines
char [] a = new char[100];
int length = fromServer.read(a);
System.out.println("Client: "+(new String(a)).substring(0,length));
Instead of these
String ip = fromServer.readLine();
System.out.println("Client: "+ ip);
Ok so after indexing the line with an '\n' and putting the line :
Socket socket = serverSocket.accept();
inside the while loop in stead of inside try{} i got rid of all my problems.
Thanks, now i'll try to multithread this thing!

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() )

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

Communication between Client and Server using Sockets

Okay this is a revised question from earlier today, I have included code to help explain the problem. I am sending two messages from the client to the server. The server then picks the messages up and processes them. The server finally attempts to send a message back to the client(please note in the server code "testmessage"), it is here I am having problems. Either I am not recieving the message at the client side or sending it incorrectly from the server side.
public class ClientConnection {
String address, language, message;
int portNumber;
Socket clientSocket = null;
public ClientConnection(String lan, String mes, String add, int pn) throws IOException{
address = add;
portNumber = pn;
language = lan;
message = mes;
}
public String createAndSend() throws IOException{
// Create and connect the socket
Socket clientSocket = null;
clientSocket = new Socket(address, portNumber);
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Send first message - Message is being correctly received
pw.write(language+"\n");
pw.flush();
// Send off the data
// Send the second message - Message is being correctly received
pw.write(message);
pw.flush();
pw.close();
// Send off the data
// NOTE: Either I am not receiving the message correctly or I am not sending it from the server properly.
String translatedMessage = br.readLine();
br.close();
//Log.d("application_name",translatedMessage); Trying to check the contents begin returned from the server.
return translatedMessage;
}
Server Code:
public class ServerConnection {
public static void main(String[] args) throws Exception {
// Delete - Using while loop to keep connection open permanently.
boolean status = false;
while( !status){
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// Delete - Working as of here, connection is established and program runs awaiting connection on 4444
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String language = br.readLine();
String message = br.readLine();
// Test - Works
System.out.println(language);
// Test - Works
System.out.println(message);
// Delete - Working as of here, both messages are passed and applied. Messages are received as sent from client.
TranslateMessage tm = new TranslateMessage();
String translatedMessage = tm.translateMessage(language, message);
// NOTE: This seems to be where I am going wrong, either I am not sending the message correctly or I am not receiving it correctly..
// PrintWriter writer = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream()));
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(),true);
// Send translation back
System.out.println(translatedMessage);
// pw.write(translatedMessage+"\n");
pw.write("Return test"); // Test message!
pw.flush();
// Send off the data
pw.close();
br.close();
clientSocket.close();
serverSocket.close();
}
}
}
The code is a bit of a mess and I can see a few duplicates, I have commented where I feel the problems occour.
Thanks for any help!
You are using BufferedReader.readLine() to read the response from the server, but in the test case you are sending a string that is not terminated with a \n or \r\n, so it will not get the line as far as I can tell from the docs...
public String readLine()
throws IOException
Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
An additional suggestion...
When writing request response protocols like this I would not rely on line endings to terminate the requests or responses. Typically I would use either a fully formatted JSON string, or my preference is for a binary protocol where all requests and response are prepended with a binary count (usually 4 bytes bigendian/network byte order). Then the client and server reads the 4 bytes then reads the number of bytes that follow. This handles the packet fragmentation that typically happens over network connections, also it helps avoid DOS attacks by malicious users sending long strings that never terminate.
In Java you can use ByteBuffer.order() to handle bigendian numbers.

Categories

Resources