Why is the message never delivered? - java

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

Related

Java Server Thread Null Pointer Exception error raised after trying to encode / decode strings into UTF-8 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm trying to create a program where a client and server send text messages to each other (in utf-8 string format) similar to how two phones text message each other. Eventually I will need to create four lines (two to encode/decode utf-8 string on server side) (two to encode/decode utf-8 string on client side) This program uses two threads, one for the client one for the server.
Screenshot of error in mac terminal (command prompt)
There were no errors before I changed the following lines of code:
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
There are three files: the main function file, the server file, and the client file. When the main function file runs, if the "-l" command line argument is present, the server file will run, otherwise the client will run.
Server file (DirectMessengerServer.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerServer
{
private static Socket socket;
boolean KeepRunning = true;
void ServerRun(String[] args)
{
Thread Server = new Thread ()
{
public void run ()
{
System.out.println("Server thread is now running");
try
{
System.out.println("Try block begins..");
int port_number1= Integer.valueOf(args[1]);
System.out.println("Port number is: " + port_number1);
ServerSocket serverSocket = new ServerSocket(port_number1);
//SocketAddress addr = new InetSocketAddress(address, port_number1);
System.out.println( "Listening for connections on port: " + ( port_number1 ) );
while(KeepRunning)
{
//Reading the message from the client
String MessageFromClientEncodedUTF8 = "";
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromClientDecodedFromUTF8 = BufReader1.readLine();
System.out.println("The message is currently encoded UTF-8");
byte[] bytes = MessageFromClientEncodedUTF8.getBytes("UTF-8");
String MessageFromClientDecodedUTF8 = new String(bytes, "UTF-8");
System.out.println("Message received from client (decoded utf-8): "+ MessageFromClientDecodedUTF8);
//Shut down with zero-length message
if(MessageFromClientDecodedFromUTF8.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
if(MessageFromClientDecodedFromUTF8=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
serverSocket.close();
}
//creating message to server send from standard input
String newmessage = "";
try {
// input the message from standard input
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null && KeepRunning==true )
{
newmessage += line + " \n ";
}
}
catch ( Exception e ) {
System.out.println( e.getMessage() );
}
//Writing return message back to client
String returnMessage = newmessage;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage + "\n");
System.out.println("Message sent to client: "+returnMessage);
bw.flush();
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Server.start();
}
}
Client file (DirectMessengerClient.java):
import java.io.*;
import java.net.*;
import java.util.*;
import static java.nio.charset.StandardCharsets.*;
public class DirectMessengerClient
{
boolean KeepRunning = true;
private static Socket socket;
//static String[] arguments;
//public static void main(String[] args)
//{
// arguments = args;
//}
public DirectMessengerClient()
{
//System.out.println("test.");
}
public void ClientRun(String[] args)
{
Thread Client = new Thread ()
{
public void run()
{
System.out.println("Client thread is now running");
try
{
System.out.println("Try block begins..");
String port_number1= args[0];
System.out.println("Port number is: " + port_number1);
int port = Integer.valueOf(port_number1);
System.out.println("Listening for connections..");
System.out.println( "Listening on port: " + port_number1 );
while(KeepRunning)
{
String host = "localhost";
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);
//creating message to send from standard input
String newmessage = "";
try
{
// input the message from standard input
BufferedReader input= new BufferedReader(
new InputStreamReader(System.in));
String line = "";
System.out.println( "Standard input (press enter then control D when finished): " );
while( (line= input.readLine()) != null )
{
newmessage += line + " ";
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() );
}
String sendMessage = newmessage;
bw.write(sendMessage + "\n"); // <--- ADD THIS LINE
bw.flush();
System.out.println("Message sent to server: "+sendMessage);
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String MessageFromServer = br.readLine();
System.out.println("Message received from server: " + MessageFromServer);
if(MessageFromServer.equals(""))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer.equals(null))
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer==null)
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
if(MessageFromServer=="\n")
{
KeepRunning=false;
System.out.println("Shutting down");
System.exit(0);
socket.close();
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
Client.start();
}
}
Main function file (DirectMessengerCombined.java):
public class DirectMessengerCombined
{
public static void main(String[] args)
{
DirectMessengerClient Client1 = new DirectMessengerClient();
DirectMessengerServer Server1 = new DirectMessengerServer();
for (int i = 0; i < args.length; i++)
{
if(!args[0].equals("-l"))
{
Client1.ClientRun(args);
}
switch (args[0].charAt(0))
{
case '-':
if(args[0].equals("-l"))
{
Server1.ServerRun(args);
}
}
i=args.length + 20;
}
}
}
My question is: How do I change the way the strings are encoded or decoded in order to send strings to the other side or how to solve the null pointer exception error?
It is because you are trying to get the inputstream of a socket before it exists:-
BufferedReader BufReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
socket = serverSocket.accept();
These two lines should be the other way around. :)
EDIT: Looking further at your code, you are creating BufReader1 (which is causing the error) and then creating br in exactly the same way, i.e. both are a BufferedReader of the socket. You only need one; having two will probably cause problems for the readers.

Socket Java - Client receives a wrong information

I am trying to send two numbers via Socket. The Server receive the numbers and I make some calculation, but when I send back to Client the result, the Client receive a number which he send it.
Where I doing wrong beceause I don't understand?
Client.java
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25010;
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 number2 = "5";
String sendMessage = number + "\n";
String sendMessage2 = number2 + "\n";
bw.write(sendMessage);
bw.write(sendMessage2);
bw.flush();
System.out.println("Message sent to the server:\n" + sendMessage + sendMessage2);
//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();
}
}
}
}
Server.java
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25010;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port " + port);
ArrayList<String> arr = new ArrayList<String>();
//Server is running always. This is done using this while(true) loop
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null) {
out.println(inputLine);
arr.add(inputLine.trim());
}
System.out.println("Message received from client is:");
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
//Return message
String returnMessage = null;
try {
int numberInIntFormat = 0;
int num = 1;
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
numberInIntFormat = Integer.parseInt(arr.get(i));
num = num * numberInIntFormat;
}
arr.clear();
returnMessage = String.valueOf(num);
} 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.
bw.write(returnMessage);
bw.flush();
System.out.println("returnMessage = " + returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e) {}
}
}
}
Your server code echoes everything it reads from the client back to the client before it does anything else with it:
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null) {
out.println(inputLine); // <-- HERE
arr.add(inputLine.trim());
}
It is unsurprising that the client receives what the server sent.
Try this:
Client:
public class Client {
private static Socket socket;
public static void main(String args[]) {
try {
String host = "localhost";
int port = 25010;
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 number2 = "5";
String sendMessage = number + "\n";
String sendMessage2 = number2 + "\n";
bw.write(sendMessage);
bw.write(sendMessage2);
bw.newLine(); // You need to send a special line for say to the server: "Hey, I have done";
bw.flush();
System.out.println("Message sent to the server:\n" + sendMessage + sendMessage2);
//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();
}
}
}
}
Server:
public class Server {
private static Socket socket;
public static void main(String[] args) {
try {
int port = 25010;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port " + port);
ArrayList<String> arr = new ArrayList<String>();
//Server is running always. This is done using this while(true) loop
while(true) {
//Reading the message from the client
socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); // primeste mesaj de la client
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // transmite raspuns catre client
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String inputLine;
while ((inputLine = br.readLine()) != null && inputLine.length() > 0) { // You need to stop loop when you get empty line
// out.println(inputLine);
arr.add(inputLine.trim());
System.out.println("Message received from client is:"+inputLine.trim());
}
System.out.println("Message received from client is:");
//Return message
String returnMessage = null;
try {
int numberInIntFormat = 0;
int num = 1;
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
numberInIntFormat = Integer.parseInt(arr.get(i));
num = num * numberInIntFormat;
}
arr.clear();
returnMessage = String.valueOf(num);
} 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.
bw.write(returnMessage+"\n"); // You need to add '\n' otherwise readLine never gets;
bw.flush();
System.out.println("returnMessage = " + returnMessage);
System.out.println("Message sent to the client is "+ returnMessage);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch(Exception e) {}
}
}
}
String inputLine;
while ((inputLine = br.readLine()) != null) {
arr.add(inputLine.trim());
}
With this change, the output is:
Server:
Server Started and listening to the port 25010
Client:
Message sent to the server:
2
5
And now the Server is 'blocked' in while loop and the Client don't recive any feedback.
I found a better method:
while (br.ready() && (inputLine = br.readLine()) != null)
This tell that to read the buffer if it is something to read.
With the response from #John Bollinger, the buffer read only up to first line break, so if you try to parse a String which contains a line break, you will get out when appear the line break.
With br.ready() it will parse all the String and will get out at the end of buffer.

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

Cannot send commands via Sockets

I'm new to the world of Java and now I'm trying to create a socket program. I created a server and a client, but they didn't seem to work. Now I post the code.
This is the server:
import java.net.*;
import java.io.*;
public class TCPCmdServer
{
public int port;
public ServerSocket server;
TCPCmdServer (int port)
{
this.port = port;
if(!createServer())
System.out.println("Cannot start the server");
else System.out.println("Server running on port " + port);
}
public boolean createServer ()
{
try
{
server = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdServer tcp = new TCPCmdServer(5000);
boolean flag = true;
while (flag)
{
try
{
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
String cmd = in.readLine();
System.out.println("Recieved: " + cmd);
if (cmd.equals("END"))
{
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
flag = false;
}
else
{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null)
{
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
}
And this is the client:
import java.net.*;
import java.io.*;
public class TCPCmdClient
{
public Socket socket;
public int port;
public String ip;
TCPCmdClient (String ip, int port)
{
this.ip = ip;
this.port = port;
if (!createSocket())
System.out.println("Cannot connect to the server. IP: " + ip + " PORT: " + port);
else System.out.println("Connected to " + ip + ":" + port);
}
public boolean createSocket ()
{
try
{
socket = new Socket(ip, port);
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
public static void main (String [] args)
{
TCPCmdClient client = new TCPCmdClient("127.0.0.1", 5000);
try
{
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(client.socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream()));
String response = in.readLine();
System.out.println("Server: " + response);
boolean flag = true;
while (flag)
{
System.out.println("Type a command... type END to close the server");
String cmd = sysRead.readLine();
out.write(cmd + "\n");
out.flush();
if (cmd.equals("END"))
{
client.socket.close();
sysRead.close();
in.close();
out.close();
flag = false;
} else
{
String outputline;
while ((outputline = in.readLine()) != null)
System.out.println(outputline);
}
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
[old]
I believe the problem is with the input and output streams, but I can't understand why they don't work.
The expected behavior is as follows: The client connects to the server then the server send response. The client asks the user to insert a MS-DOS command (or a "END" command), the command is then sent to the server. The server executes the command on the computer where it is running (in case the command is END it closes the connection). Then the server sends the result of the command to the client, and the client displays it to the user.
[/old]
Now the only problem is that I have to close and re-open a client any time I like to execute a new command
In your server code, you are creating a new socket for every command you received from the client. That is why you have to open a new client every time you want to send a command to the server. To correct this, first you need to remove the while(flag) loop in server code. Then you can use the following to establish the connection to the client and send and receive command and output between them.
Socket socket = tcp.server.accept();
System.out.println("A client has connected");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
try {
while(!(cmd = in.readLine()).equals("END")) {
System.out.println("Recieved: " + cmd);
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader pRead = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = pRead.readLine()) != null) {
System.out.println(line);
out.write(line + "\n");
out.flush();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
System.out.println("Shutting down server...");
socket.close();
in.close();
out.close();
}
In TCPCmdServer.java, try changing
out.write("Welcome on the server... type the commands you like, type END to close me");
to
out.write("Welcome on the server... type the commands you like, type END to close me\n");
out.flush();
Also, change
out.write(buffer.toString());
to
out.write(buffer.toString() + "\n");
out.flush();
In TCPCmdClient.java
change
out.write(cmd);
to
out.write(cmd + "\n");
out.flush();
response = in.readLine();
System.out.println("Server: " + response);

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