Java: Buffered Reader waiting for input before updating - java

I am programming a small ChatServer program, and I've nailed down the error to this part of the client code
public void run() {
Client client = new Client();
try {
Socket s = new Socket("localhost", 25555);
client.os = new DataOutputStream(s.getOutputStream());
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
while (!exit){
String str = Input.read_string();
client.os.writeUTF(ID+"=CLID"+str.toLowerCase());
client.os.flush();
System.out.println(br.readLine());
}
} catch ( IOException e) {
e.printStackTrace();
}
}
The Input.read_string() code is the following:
class Input{
public static String read_string() {
String read="";
try {
read = new BufferedReader(new InputStreamReader(System.in), 1).readLine();
} catch (IOException ex) {
System.out.println("error reading from the input stream!");
}
return read;
}
}
When I put the System.out.println(br.readLine()); at the beginning of the while loop the first time another client chats, but after that one has to input to get the next update.
Also, this may be fixed with the last error, but when it does update, it is the last thing the other client sent.

Related

java.io.EOFException: at java.io.DataInputStream.readUTF(Unknown Source) - write file line by line

I made a simple Server-Client application to read line by line file from Server and write line by line in a new file in the client side. The application writes corretcly the lines in the file , but when the file reaches the end, I catch this error:
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at it.sendfile.socket.FileClient1.main(FileClient1.java:19)
my code:
public class FileServer1 {
public static void main(String[] args) {
int port = 3000;
// open server socket
ServerSocket ss = null;
try {
ss = new ServerSocket(port);
Socket s = ss.accept();
DataOutputStream outToClient = new DataOutputStream(s.getOutputStream());
File testFile = new File("C:\\temp\\tmpbgoutcoge");
BufferedReader input = new BufferedReader(new FileReader(testFile));
String line;
while ((line = input.readLine()) != null) {
outToClient.writeUTF(line);
outToClient.writeUTF("-----------------------------");
outToClient.flush();
Thread.currentThread().sleep(1000);
}
input.close();
outToClient.close();
s.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
public class FileClient1 {
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(new FileWriter("C:\\temp\\tmpbgoutcoge1.txt", true));) {
Socket s = new Socket("localhost", 3000);
DataInputStream inFromServer = new DataInputStream(new BufferedInputStream(s.getInputStream()));
while (true) {
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have to find a While stop condition when I reach the end of file, but I've tryied with (line = inFromServer.readUTF())!= null but it's not worked.
In the FileClient1 class, I can't close the socket and the DataInputStream. A message says:"Unreachable code".
readUTF() will never return null. You need to send a “sentinel value” before closing—a special value that indicates the end of the stream.
Obviously you want it to be something that is very unlikely to be sent in a normal use case. I suggest "\uffff" (a String with length 1), since U+FFFF is guaranteed not to be a defined character.
You can use
while(inFromServer.available()>0) {
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("\n");
}
instead of
while (true) {
String line = inFromServer.readUTF();
System.out.println(line);
out.write(line);
out.println("\n");
}

How to receive input from client in server?

How do I send input on the client console to the server? So far I have
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
How do I get 'input' in the server side? What must I call on the clientSocket? I've tried this:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
out.write(input);
And on the server side:
serverSocket = new ServerSocket(port);
while(true) {
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input = in.readLine();
if (input.equals("2")) {
System.out.println("activate receiveFile");
receiveFile();
}
However 'input' is certainly not '2' when I enter 2.
Try using PrintWriter(Writer out, boolean autoFlush) constructer when creating PrintWriter object. Eg: out = new PrintWriter(echoSocket.getOutputStream(), true);
server side contructor
try {
is = new BufferedReader(new InputStreamReader(new BufferedInputStream(soc.getInputStream())));
os = new PrintWriter(new BufferedOutputStream(soc.getOutputStream()), false);
printWriterQueue = new PrintWriterQueue(this, os, is, timeout);
soc.setSoTimeout(5000);
start();
} catch (Exception e){
e.printStackTrace();
}
you should use a thread so in the run
while (!end) {
do {
try {
st=is.readLine();
} catch (InterruptedIOException ie) {
st="";
}
} while (!end && st.length()==0);
client side contructor
soc = new Socket(IpAddress, 2999);
in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
out = new PrintWriter(soc.getOutputStream());
addText("Connection up and running...");
soc.setSoTimeout(5000);
printWriterQueue = new PrintWriterQueue(this, out, in, 10000);
Thread th=new Thread(this);
th.start();
a thread for the client too so in the run()
try {
do {
do {
try {
msg=in.readLine();
} catch (InterruptedIOException ie) {
msg="";
}
} while (!end && msg.length()==0);
if (!end) {
System.out.println("["+msg+"]");
}
} while (!end);
} catch (Exception exc) {
exc.printStackTrace();
}

Java cannot read and write to socket at the same time

I am trying to build a simple multi client chat application using java sockets. The way I have gone about doing this is by having a client class that connects to a server class that waits for clients to connect and creates a new thread to deal with that client(Where the socket connection is read and written to). The client also reads from and writes to the socket connection to this thread. However, when the client wrote to the output stream of the socket, the server would not respond. A similar question here was posted:
Can you write to a sockets input and output stream at the same time?
One of the answers here says that you can read and write to a socket at the same time as long as reading from the socket is done on a separate thread.
Here is my client application:
public class Client {
Socket socket;
public static void main(String[] args) {
new Client();
}
public Client() {
try {
socket = new Socket("localhost", 4444);
new Thread() {
#Override
public void run() { //read from the input stream
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Server said: " + line);
}
} catch(IOException e) {
}
}
}.start();
//write to output stream
try(
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Scanner userInput = new Scanner(System.in);
){
System.out.println("Enter Something: ");
if(userInput.hasNextLine()) {
out.println(userInput.nextLine());
}
} catch (IOException e) {
}
} catch(IOException e) {
}
}
}
And my server application:
public class Server {
ServerSocket ss;
public static void main(String[] args) {
new Server();
}
public Server() {
System.out.println("Server Running...");
try {
ss = new ServerSocket(4444);
while(true) {
Socket socket = ss.accept();
new Thread() { //create new thread connection to client
#Override
public void run() {
new Thread() { //thread that reads inputstream
#Override
public void run() {
try(
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
String line;
while( (line = in.readLine()) != null ) {
System.out.println("Client said: " + line);
//The problem seems to lie here.
}
} catch(IOException e) {
}
}
}.start();
//write to outputstream
try (
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
) {
String sendToClient = "Hey, my name is Server007 B)";
out.println(sendToClient);
} catch(IOException e) {
}
}
}.start();
}
} catch (IOException e) {}
}
}
I will run the server, then run the client, on the client side the output is
Server said: Hey, my name is Server007
Enter something:
Hello! <- enter anything
but the server does not print 'Client said: Hello!' like I expected it to. I hope I made my problem clear enough, thanks.
Ok, so I figured it out, I will answer my own question in case anyone makes the same mistake. The PrintWriter constructor should be this:
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Not this:
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Alternatively, I could have done this:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
I must have just gotten confused between BufferedWriter and PrintWriter :P

Java Socket Communication "deadlock"

Hi I am trying to implement server operating with multiply clients
The problem is that the server does not receive the message from inputstream and wait until it happen. if the client don't close the stream after writing to it the server will continue to wait. After the client send the message, he try to read from the inputstream waiting for response, but the server is waiting for the request. So.. deadlock
This is my client class
public class Client implements Runnable{
...
#Override
public void run() {
BufferedReader is = null;
BufferedWriter os = null;
try(Socket socket = new Socket(address.getHostName(), address.getPort());){
String request = String.format("%s-%d-%s",this.destination, this.desiredPlace, this.paymentMethod.toString());
os = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(os, true);
pw.write(request);
pw.flush();
// if I close the stream here the request will be send, but this will close the socket so the I will not receive response.
String response;
while ((response = is.readLine()) != null){
System.out.println(response);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And this is my server class
public void perform() throws IOException, DestionationProcessingException, InterruptedException {
try (ServerSocket server = new ServerSocket(port);) {
StandalonePayDesk offLinePayDesk = new StandalonePayDesk(ticketManager);
this.threadPool.submit(offLinePayDesk);
while (true) {
Socket socket = server.accept();
RequestHandler handler = new RequestHandler(this.threadPool, offLinePayDesk, this.ticketManager);
handler.process(socket);
}
}
}
and RequestHandler class for processing each client
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true)) {
writer.println("hello");
writer.flush();
String line;
while ((line = reader.readLine()) != null) {
String[] lineTokens = line.split("-");
...
Can anyone help me to solve this problem ?
pw.write(request);
Your client is writing a request but not a line. Your server is reading a line, with readLine(), and will block until the line terminator arrives, which is never, so it will never send a reply, so your client will never receive it, so it will block forever.
Change the above to:
pw.println(request);

BufferedWriter.write() does not seem to work

I have two Java applications, where an Android client connects to a server on a computer and sends a message using BufferedWriter over websockets.
The client:
try {
toast("Sending...");
Socket sock = new Socket(ip, PORT);
OutputStream os = sock.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
bw.flush();
bw.write("Hello Server!");
toast("Connected!");
} catch (UnknownHostException e) {
toast(e.getMessage());
} catch (IOException e) {
toast(e.getMessage());
}
The server:
public static void main(String[] args) {
ServerSocket server;
ConnectionThread ct;
Socket s;
ExecutorService es = Executors.newSingleThreadExecutor();
try {
System.out.println("Starting server...");
server = new ServerSocket(1337);
s = server.accept();
ct = new ConnectionThread(s);
es.execute(ct);
} catch (IOException ex) {
ex.printStackTrace();
}
}
The ConnectionThread class:
public class ConnectionThread implements Runnable {
private Socket sock;
private InputStream is;
private BufferedReader br;
private boolean online;
public ConnectionThread(Socket s) {
System.out.println("Creating connection thread.");
this.sock = s;
online = true;
}
#Override
public void run() {
String input = "";
try {
System.out.println("Starting to read...");
is = sock.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while (online) {
input = br.readLine();
if(input != null){
System.out.print("Received message: ");
System.out.println(input);
}
}
br.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run the server, and then the client, the client will show the "Connected!" toast, and the server's output will be:
Starting server...
Creating connection thread.
Starting to read...
So, it seems like the connection is actually being made, but the message does not arrive. Does anybody know why this could be happening?
Your server is expecting a complete line terminated by a newline. Try:
bw.write("Hello Server!");
bw.newLine();
Do it like this...
String s = new String();
while ((br.readLine())!=null) {
s = s+br.readLine();
System.out.print("Received message: ");
System.out.println(input);
}
}
And
bw.println("Hello Server");
I notice that you don't send an endline on your client, so the BufferedReader.readline() will never return, because it cannot match the \n-character. Try it again with
bw.write("Hello Server!\n");
on the client side.

Categories