PrintWriter won't write - java

I have the following problem.
I programmed a simple Echo Server and Echo Client but the problem is that in the loop of the Server, where I read from the Buffered Reader, the programme stuck and it won't write.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
String message = null;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
}
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
System.out.println(message);
writer.println(message);
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
But when i put the .println() and .flush() in the loop everything works great.
import java.net.*;
import java.util.*;
import java.io.*;
public class SimpleServer {
public static void main(String[] args) {
System.out.println("Dies ist ein simpler Echo Server");
int port = 6000;
try {
ServerSocket server = new ServerSocket(port);
//server.setSoTimeout(30000);
System.out.println("Warte auf anfrage");
Socket client = server.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
OutputStream os = client.getOutputStream();
PrintWriter writer = new PrintWriter(os);
String message;
while ((message = reader.readLine())!=null) {
System.out.println("Nachricht vom Client "+message);
writer.println(message);
writer.flush();
}
writer.close();
} catch(IOException e) {
e.printStackTrace();
} // end of try
} // end of main
} // end of class SimpleServer
My question is why does it stuck in the loop ?

You are reading the inpit until end of stream before you send anything. End of stream on a socket only occurs when the peer closes the connection. The peer hasn't closed the connection, because he wants to read your reply from it.
You should echo every line as you read it, not try to assemble them all and then echo them all in one great chunk. Apart from the fact that it can't work, your technique also wastes both time and space.

Related

TCP client not responding in JAVA

I was learning JAVA networking API and simple TCP server-client communication.
I have written the following two classes for client and server.
The issue is that my client is not responding i.e. the program is not terminating and it doesn't output anything .. Can anyone see where I am going wrong?
Client:
import java.io.*;
import java.net.*;
public class client {
public void go() {
try {
Socket s = new Socket("127.0.0.1",2323);
InputStreamReader streamReader = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String reading = reader.readLine();
PrintWriter write = new PrintWriter(s.getOutputStream());
write.print("mynameistom");
System.out.println(reading);
reader.close();
writeToServer.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client;
client.go();
}
}
Server:
package TCP;
import java.io.*;
import java.net.*;
public class Server {
public void go() {
try {
ServerSocket serverSock = new ServerSocket(2323);
Socket socket = serverSock.accept();
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
String messsage = reader.readLine();
PrintWriter writer = new PrintWriter(socket.getOutputStream())
writer.println(message);
writer.close();
System.out.println(message);
} catch(IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
}
The obvious thing is that the client isn't flushing, and is missing the new line.
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.print("network");
Should be either
PrintWriter writeToServer = new PrintWriter(s.getOutputStream(), true);
writeToServer.println("network");
or
PrintWriter writeToServer = new PrintWriter(s.getOutputStream());
writeToServer.println("network");
writeToServer.flush();

Handler thread hanging on reading in

I am trying to set up a server with a client and a handler. The client should ask for a string from the user. This should then be written to an OutputStream, get read in by the handler which then saves the string to its own OutputStream before passing it back to the client. I know that this program is completely pointless, I am just trying to get my head around how servers, clients and handlers work.
Here is my code so far:
Server
public class Server {
public static void main (String args[]) throws IOException {
int port = 8080;
ServerSocket server = new ServerSocket(port);
while (true) {
System.out.println("Waiting for client...");
Socket client = server.accept();
System.out.println("Client from "+client.getInetAddress()+" connected.");
Handler handler = new Handler(client);
handler.run();
}
}
}
Handler
class Handler extends Thread {
private Socket client;
public Handler(Socket c) {
client = c;
}
public void run() {
try {
Thread.sleep(3000);
System.out.println("1");
PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(client.getInputStream(),
"UTF-8"));
System.out.println("2");
String message = in.readLine();
System.out.println("4");
System.out.println("5");
out.println(message);
out.flush();
client.close();
System.out.println("Finish");
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Client
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 8080);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in =
new BufferedReader(new InputStreamReader(server.getInputStream(),
"UTF-8"));
out.println(message);
String messageReturn = in.read();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
The problem is that the handler seems to hang when it tries to read the message in. This problem seems similar to the one presented here: Socket problem - readline won't work properly
But this solution isn't working for me. I have tried using objectInputStreams instead of my current solution, but this didn't work either.
I doubt whether your client code will compile. The return type for this is int.
String messageReturn = in.read();
Anyway, this should work:
package network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main (String args[]) throws IOException {
Socket server = new Socket("127.0.0.1", 9890);
System.out.println("Attempting connection...");
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a string:");
String message = scan.next();
PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
out.println(message);
// NOTE this
String messageReturn = in.readLine();
scan.close();
System.out.println("Server said: " + messageReturn);
in.close();
out.close();
}
}
Note Port has been changed.
Server Output
Waiting for client...
Client from /127.0.0.1 connected.
1
Client Output
Attempting connection...
Please enter a string:
Hello
The problem might be that you do not send an escape sequence with your response. ReadLine() waits till it gets an escape. Try sending a "\n" with your response. There is an article about problems using readLine() and println() with sockets. It also shows how to solve it.
ReadLine() / Println() and sockets

Java Client/Server App will not readLine()

I am trying to write a program that allows the user to send a message to a server and receive a modified version of that message. For some reason, the flow of the program stops on a certain line below, which I have pointed out. Can anybody explain why this isn't working? Thanks.
Server Side
import java.net.*;
import java.io.*;
public class Server{
public final static int port = 1025;
public static void main (String[] args){
ServerSocket serverSocket;
Socket client;
PrintWriter output;
try{
serverSocket = new ServerSocket(port);
try{
while(true){
client = serverSocket.accept();
InputStream is = client.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from client is " + message);
String returnMessage = message + message;
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is " + returnMessage);
bw.flush();
}
} catch(IOException e){
serverSocket.close();
System.err.println(e);
}
} catch(IOException e){
System.err.println(e);
}
}
}
Client Side
import java.util.Scanner;
import java.net.*;
import java.io.*;
class Client{
public void getService(String destination, int port){
try{
while(true)
{
Scanner in = new Scanner(System.in);
System.out.println("Send a message to the server: ");
String message = in.nextLine();
Socket server = new Socket(destination, port);
OutputStream os = server.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String sendMessage = message + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+ sendMessage);
InputStream is = server.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message2 = br.readLine(); // I have determined that the program's flow proceeds no further than this line
System.out.println("Message received from the server : " + message2);
}
} catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
String serverAddress = args[0];
System.out.println(serverAddress);
Client client = new Client();
client.getService(serverAddress, 1025);
}
}
The server uses a BufferedReader, whose readLine method requires an end of line delimiter, but the Client is not sending it - rather, it reads the line (with end of line delimiter stripped) and attempts to echo this message. Append a new line character to the data sent by the client so that the readLine method of the Server does not block while waiting for the line:
String returnMessage = message + message + "\n";

Why is my HTTP response not showing up in my browser?

I am trying to write an HTTP server in Java. After going through examples and adding in some stuff for debugging, this is what I have so far:
import java.net.*;
import java.io.*;
import java.util.*;
public class AddyServer {
public static void main(String[] args) {
int portNumber = Integer.parseInt(args[0]);
try{
System.err.println("Trying...");
ServerSocket serverSocket = new ServerSocket(portNumber);
System.err.println("Waiting...");
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while(true) {
System.err.println("Waiting...");
Socket clientSocket = serverSocket.accept();
System.err.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
String line;
while((line=in.readLine())!=null) {
if(line.isEmpty())
break;
out.print(line+"\r\n");
System.out.print(line+"\r\n");
}
out.print("HTTP/1.1 200\r\n"); //EDITED
out.print("Content-Type: text/html\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.print("<!doctype html>\n");
out.print("<title>Test title</title>\n");
out.print("<p>Test</p>\n");
System.out.print("HTTP/1.1 200 \r\n");
System.out.print("Content-Type: text/html\r\n");
System.out.print("Connection: close\r\n");
System.out.print("\r\n");
System.out.print("<!doctype html>\n");
System.out.print("<title>Test title</title>\n");
System.out.print("<p>Test</p>\n");
in.close();
out.close();
clientSocket.close();
}
} catch (IOException e) {System.err.println(e);} //EDITED
}
}
I do not understand why my internet browser is not displaying the HTTP response body in the browser when I try connecting to my server.
Add a flush after writing to socket (via PrintWriter). Also you need to close the serverSocket at some point, otherwise, you'll have issues just testing it with port being already bound.
edit This shows exactly where you want to flush. Tested and works for me.
Working fixed code:
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class AddyServer {
public static void main(String[] args) throws Exception {
int portNumber = Integer.parseInt(args[0]);
System.err.println("Trying...");
ServerSocket serverSocket = new ServerSocket(portNumber);
System.err.println("Waiting...");
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
// true);
while (true) {
System.err.println("Waiting...");
Socket clientSocket = serverSocket.accept();
System.err.println("accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
String line;
while ((line = in.readLine()) != null) {
if (line.isEmpty())
break;
out.print(line + "\r\n");
System.out.print(line + "\r\n");
}
out.print("HTTP/1.1 200 \r\n");
out.print("Content-Type: text/html\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.print("<!doctype html>\n");
out.print("<title>Test title</title>\n");
out.print("<p>Test</p>\n");
out.flush(); // <--- Fix is here
System.out.print("HTTP/1.1 200 \r\n");
System.out.print("Content-Type: text/html\r\n");
System.out.print("Connection: close\r\n");
System.out.print("\r\n");
System.out.print("<!doctype html>\n");
System.out.print("<title>Test title</title>\n");
System.out.print("<p>Test</p>\n");
in.close();
out.close();
clientSocket.close();
}
}
}
Your output isn't getting flushed (actually sent). Use flush() on the PrintWriter and it should work.
A PrintWriter doesn't necessarily flush automatically.
My guess is that you close the socket (hence interrupting the connection) before the PrintWriter has been able to flush upon closing.
As an alternative to flushing right before closing (recommended), you could construct your PrintWriter with automatic line flushing (not recommended) as
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
In which case calls to printf, println or format will flush it (but not calls to print).

TCP socket connection

I'm new to the network communication and I'm trying to build client-server application.
protected void init(){
Server myServer = new Server();
Client myClient = new Client();
}
That's my Client class:
public class Client {
public Client() {
init();
}
private void init() {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("localhost", 1234);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
os.writeInt(stdIn.readInt());
echoSocket.getOutputStream().close();
echoSocket.getInputStream().close();
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And that's server:
public class Server {
public Server() {
init();
}
private void init() {
try {
boolean run = true;
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readInt());
s.getInputStream().close();
s.getOutputStream().close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
First of all:
Can I initialize client and server simply like i did? new Server() and new Client()?
Question 2:
Is it important what i initialize at first? client or server?
Question 3:
When i compile this code with client first initialized, i become Connection refused: connect. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using setSoTimeout and how?
Question 4:
When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe setSoTimeout goes here too?
You can't have both client and server in the same thread.
As you already have observed, the server accepts the connection and tries to read something. It doesn't know that the client is running in the very same thread.
Either make a multi-threaded application, where client and server have their own thread. Or make two prgrams that run independently of each other. The latter would be also the "normal case".
Make two different projects, first run server than client.
Server will write on console "Server started" than run client it will ask your name, type your name press ok . Your name will be sent to server and server will reply saying hello to you.
Here is server code
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss= new ServerSocket(2224);
System.out.println("Serever started");
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
String name=br.readLine();
String message="Hello "+name+"from server";
pw.println(message);
pw.flush();
}
}
catch(Exception exp)
{
System.out.println("Excepttion occured");
}
}
}
Here is client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",2224);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
String message = JOptionPane.showInputDialog("Give your name");
pw.println(message);
pw.flush();
String servermessage = br.readLine();
JOptionPane.showMessageDialog(null, servermessage);
s.close();
}
}

Categories

Resources