Java Client/Server App will not readLine() - java

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

Related

PrintWriter won't write

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.

Java Multi-threaded client/server with send/receive

I'd like to make a client that sends strings to a server occasionally, for example: when application closed it sends a message to server- sendToServer("Client[" + IP + "]Closed")
I have a problem in my code :
Server :
try{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String received = br.readLine();
System.out.println("Message received from client is "+received);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
returnMessage = "You send : " + received;
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.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 (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){
}
}
CLIENT :
try {
String host = IP;
int port = Port;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}

Client server messages in a loop

I want to send two messages at least from the client to the server and the server then responds to these messages. However only one message is sent from the client and the server also responds to one any idea where i am wrong
This is my server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class server
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sub = br.readLine();
//string parsing
String delims = "[.]";
String[] tokens = sub.split(delims);
System.out.println("You have subscribed to "+tokens[1]);
String returnMessage="Subscription message received.";
//Sending the response back to the client.
OutputStream os = socket.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();
InputStream iss = socket.getInputStream();
InputStreamReader isrr = new InputStreamReader(iss);
BufferedReader brr = new BufferedReader(isrr);
String subb = brr.readLine();
System.out.println("Regular message received from client is "+subb);
OutputStream oss = socket.getOutputStream();
OutputStreamWriter osww = new OutputStreamWriter(oss);
BufferedWriter bww = new BufferedWriter(osww);
bww.write(subb);
System.out.println("Message sent "+subb);
bww.flush();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
And this is my client.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class client
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the subscription message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String subscribe= "Subscribe.nust";
String sendMessage = subscribe + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
//Send the regualar message to the server
OutputStream oss = socket.getOutputStream();
OutputStreamWriter osww = new OutputStreamWriter(oss);
BufferedWriter bww = new BufferedWriter(osww);
String regular= "Because of the APS Peshawar attack that took place on 16th December 2014, nust is facing security issues.";
String sendMessage2 = regular + "\n";
bww.write(sendMessage2);
bww.flush();
System.out.println("Message sent to the server : "+sendMessage2);
//Get the return message from the server
InputStream iss = socket.getInputStream();
InputStreamReader isrr = new InputStreamReader(iss);
BufferedReader br1 = new BufferedReader(isrr);
String msg = br1.readLine();
System.out.println("Message received from the server : " +msg);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Don't keep creating new BufferedReaders/Writers on the same socket. Use the same ones for the life of the socket. You're losing data in their buffers.

Why is the message never delivered?

For some reason, i never get the message back from the server to the client :/ whats happening? how can i know or solve this?
I send the request from the client, the server gets that request, process it and generate a response that is send. But the client never reads it.
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 13579;
System.out.println("Conecting to : " + host + ":" + port);
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String sendMessage = "103700635105281047295162150000001418 99900001000000717999000NovoTransactionsBusiness 717 VE000000000054300052810472900000000000099900001 1803\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : " + sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
//But i never get the message back
String message = br.readLine();
System.out.println("Message received from the server : " + message);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
//Closing the socket
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The server is running fine!
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 13579;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Servidor Iniciado escuchando al puerto " + port);
while (true) {
socket = serverSocket.accept();
String strRequest = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
System.out.println("Request Received: " + strRequest);
String returnMessage;
try {
returnMessage = new NovoTrans().init(strRequest).toString();
} catch (Exception e) {
returnMessage = "Error: " + e.getMessage() + "\n";
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(returnMessage);
System.out.println("Sending Message: " + returnMessage);
bw.flush();
}
} catch (Exception e) {
} finally {
try {
socket.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
I suggest you to use PrintWriter instead of BufferedWriter. There is no need to call flush after each line and simply use println() method along with auto-flush feature to add a new line as well.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output.
These methods use the platform's own notion of line separator rather than the newline character.
There is no need to append \n in the message itself.
Sample code: (Do the changes in both server and client side classes)
// here true means auto flush when `println()` method is called
PrintWriter bw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
bw.println(returnMessage);

tcp connection stuck in close_wait java

There are lot of close_wait connection, when ever a client client sends the message to the server and comes out the TCP FSM stuck in the CLOSE_WAIT STATE
This the Client code,
public class Client1
{
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This the Server code which listen to the upcoming connection
public class Server1
{
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
//Server is running always. This is done using this while(true) loop
while(true)
{
//Reading the message from the client
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
//Sending the response back to the client.
OutputStream os = socket.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 (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
The output TCP FSM
-bash:~$ netstat -an | grep 25000
tcp4 0 0 127.0.0.1.25000 127.0.0.1.56459 CLOSE_WAIT
tcp46 0 0 *.25000 *.* LISTEN
You're closing the accepted socket in the wrong place. It needs to be inside the accept loop.

Categories

Resources