Client/Server Programming - java

I am practicing a simple java program where I am demonstrating simple client server interaction. The fist part of message from server gets transferred. Then program just continues to run and does not execute? Do we need to create a new socket for each individual traffic?
Server code
server = new ServerSocket(4587);
System.out.print("Starting the Server on port " + server.getLocalPort() + "\n");
System.out.println("Waiting for client...");
Socket client = server.accept();
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader br1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
br.write("Hello, you are connected to Server. What is your name?");
br.write("\n");
br.flush();
while((s=br1.readLine())!=null)
{
}
br.write("Thank you ");
br.newLine();
br.flush();
}
Client code
String stdin;
System.out.println("Attempting to connect to " + hostname + ":" + port);
client = new Socket("localhost", 4587);
System.out.println("Connection Established");
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
BufferedWriter br1 = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
br1.write("Mike");
br1.write("\n");
br1.flush();
while ((stdin = br.readLine()) != null) {
System.out.println(stdin);
}
Server Output
Starting the Server on port4587
Waiting for client....
Client Output
Attempting to connect to :123
Connection Established
Hello you are connected to Server, What is ur name
If this could help..after this both loop

Your server will first create a connection with the client through the accept method. If you wish to have multiple clients you will need to change your code accordingly to accept that.
On the client side, you're using \n to delineate the end of a message. This will work fine. Every time you send a new message use \n to indicate the end of the message.
On the server side, you should continue reading from I/O until you see the \n. At that point you have received the entire message. Process it and than start listening again.
Edit:
Since you are waiting for the name of the client, you could simply do the following on the server:
BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
BufferedReader bin = new BufferedReader(new InputStreamWriter(client.getInputStream()));
// Wait for incoming name from client.
String name = bin.readline();
System.out.println(name);
// Send a reply.
bout.write("Thank you\n");
bout.flush();
Similarly, on the client (assuming bin and bout are defined the same as above):
// Send name to server.
bout.write("Name\n");
bout.flush();
// Get a response from the server and print to console.
String response = bin.readline();
System.out.println(response);

This is because BufferedReader has a default buffer = 8K when in reading process and this process is block I/O, so this will hang in that point. You should read the full message from client by server side.

Your problem is with the loop on the client side. It will be stuck in the loop as it waits to readlines sent from the server infinitely. (ie, after reading the first line from the server, it will expect more lines from the server and wait to read them).
To exit the loop you need to send an EOF signal or end of stream signal (according to the docs: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine%28%29)

Related

Why server side socket is not receiving messages after reading "\n.\n"

I have written simple java client/server program and client is trying to sent like below:
os = new DataOutputStream(socket.getOutputStream());
os.writeBytes("HELO\n");
os.writeBytes("MAIL From: person#example.com\n");
os.writeBytes("RCPT To: to#example.com\n");
os.writeBytes("DATA\n");
os.writeBytes("From: person#example.com\n");
os.writeBytes("Subject: testing\n");
os.writeBytes("Hi there\n"); // message body
os.writeBytes("\n.\n");
os.writeBytes("QUIT");
But my server side socket is able to read upto "\n." and then it is waiting to read.
Why is it not reading "QUIT" message after "\n.\n"
Server code:
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
You need to put a "\n" after QUIT, the stream is reading QUIT, but it doesn't cause the is.readLine() because theres no "new line" character in the string

Client's BufferedReader not recieving line from Server, using sockets (Java)

I'm trying to make a chat application between a server and clients which are seperate classes. I'm not copying the whole code, but this is the part I'm not sure is set up correctly:
Server:
ServerSocket s = null;
Socket c = null;
s = new ServerSocket(5002);
c = s.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()))
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
out.flush();
String line;
line = in.readLine();
out.write("#W|Welcome");
line = in.readLine();
out.write("#W|Welcome");
line = in.readLine();
out.write("#W|Welcome");
Client :
Socket socket = new Socket("localhost", 5002);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream ()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String line;
out.flush();
out.write("#J|test");
line = in.readLine();
out.write("#J|test");
line = in.readLine();
After the client does out.println(), the server's in.readLine() gets the line. But when it's the other way around, the client keeps waiting at in.readLine(). (I used the debugger and watched the server execute out.println() and go past it, while the client is still stuck at in.readLine().
Are my data streams set up correctly or is there probably an error in my code somewhere else? I'm not sure how to check in the debugger if the streams are connected correctly.
[Quoting my comment above:]
There is nothing here that [reads or] writes lines.
That remains true. All you have is:
out.write("#W|Welcome");
etc.
don't forget to call newLine() as necessary
You forgot.

Java TCP socket blocks at readLine

I'm working on a TCP client/server application and face the issue that the client is always blocking at br.readLine(). I tried to add a \n, but it did not solve the problem. Also a char array is blocking, when I only use read instead of readLine.
Client:
BufferedReader brInput = new BufferedReader(new InputStreamReader(System.in));
String send = brInput.readLine();
Socket socket = new Socket(host, port);
BufferedReader brSend = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pr = new PrintWriter(socket.getOutputStream());
pr.println(send);
pr.flush();
System.out.println(brSend.readLine()); // is blocking
socket.close();
Server:
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept(); // blocks until request is received
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
if (line.isEmpty()) break;
}
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.write("Hello world\n");
pw.flush();
pw.close();
socket.close();
}
Your code as written does this:
The client writes one line, and then tries to read one.
The server reads multiple lines until it either gets an empty line, or the end-of-stream. Then it writes a line.
The problem is that server is waiting for the client to do something that it isn't going to do:
the client won't send an empty line (unless it read one from standard input),
the client won't close the stream ... until it gets the response from the server.
Hence the client is waiting for the server and the server is waiting for the client. Deadlock.
There are various ways to solve this. One simple way would be to change this (in the client)
println(send);
to this
println(send); println();
However, the one problem here is that your "protocol" does not cope with the case wants to send an empty line as data. That is because you are implicitly using an empty line (from the client) to mean "message completed".

readLine() never stops reading

inFromClientR.readLine() never stops. any ideas? Am I forgetting something?
Server:
/*{ some code:
send a file with a dataoutputstream to client using a new port(4000) and when transfer is done i want a responce message (e.g. OK) send back to server in the old port(6000)
}*/
ServerSocket listenTransferSocket = new ServerSocket(6000);
Socket connectionTransferSocket = listenTransferSocket.accept();
BufferedReader inFromClientR =
new BufferedReader(new InputStreamReader(connectionTransferSocket.getInputStream()));
System.out.println("Client's response to Transfer: " +inFromClientR.readLine());
Client:
/*{ some code:
receive the file on port (4000) and then the responce is sent to server using the following commands
}*/
Socket fileTransferSocket = new Socket("localhost", 6000);
DataOutputStream outToServerR =
new DataOutputStream(fileTransferSocket.getOutputStream());
outToServerR.writeBytes("Transfer completed " +'\n');
BufferedReader#readLine() tries to fill its buffer with 8192 bytes, regradless of any linefeeds it find meanwhile. Since you have the connection open, the receiving side will wait until 1) you have sent 8192 bytes, or 2) closes the connection.
You would be better off using some other framing mechanism, maybe an ObjectOutputStream/ObjectInputStream.
String line = null;
while ((line = inFromClientR.readLine()) != null) {
// do sth
}

TCP connection Socket.getInputStream()

I created an application which establishes connection with the given port and transport data either ways. But I am having issues in reading the data from the server.
try{
Socket skt = new Socket(127.98.68.11, 1111); // connecting to this to get data
String message = "some test message";
if(option.equalsIgnoreCase("send")){
OutputStream outToServer = skt.getOutputStream();
outToServer.write(message); // this is working, message stored on server-side
}else if(option.equalsIgnoreCase("receive")){
BufferedReader in = new BufferedReader (new InputStreamReader(sit.getInputStream()));
String fromServer = in.readLine();
System.Out.Println(fromServer);
}
}catch(IOException io){
io.printStackTrace();
}
In this program everything is working as expected. except in.readline().
I tried running this program in debugging mode, and the by the time compiler reaches this command. is was doing nothing and i can't see the cursor also
It could be because you are trying to do an in.readLine() this requires that the server terminates the "receive" command which it is sending to the client with a newline.. "\n" or "\r\n" along

Categories