Client not able to receive messages from Server Socket programming Java - java

I am trying to make a chat system through terminal. One computer acts as server, the other as client.
Here is my code for Client side :
try
(
Socket s = new Socket(hostname,port);
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
) {
String input;
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
// out.close();
// stdIn.close();
// s.close();
}
catch (UnknownHostException e)
{
System.err.println("Don't know about host: " + hostname);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O");
System.exit(1);
}
Here is my code for Server side:
System.out.println ("New communication thread started.");
try
{
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String input;
String inputline;
while ((inputline = in.readLine()) != null)
{
System.out.println("Them: " + inputline);
}
while ((input = stdIn.readLine()) != null)
{
out.println(input);
}
}
catch (IOException exx)
{
System.err.println("Some problem");
System.exit(1);
}

You are using stdIn.readLine() on System.in but that stream can never terminates (of course).
So you should change your condition.
while ((input = stdIn.readLine()) != null) // Your problem is here
Have you checked if you reach the second while?
Try this in both server and client:
input = stdIn.readLine();
out.println(input);

Related

What's causing my SocketException: Connection reset?

In any iteration within the while, a SocketException: Connection reset is generated. can someone give me some suggestions?
logger.info("Start send xml");
StringBuilder bld = new StringBuilder();
try (Socket socket = new Socket(ipAddress,port)){
socket.setSoTimeout(600000);
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);
writer.println(xml);
writer.flush();
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null)
bld.append(line);
writer.close();
reader.close();
} catch (IOException e) {
logger.error("Error sending the XML");
logger.error(e.getMessage());
throw new SendXMLException(e.getMessage());
}
logger.info("End Send xml -> " + bld.toString());
return bld.toString();

How to use BufferedReader before PrintWriter in Java

I am working on small Server/ Client application (console base) in Java. The purpose of the application is to send number from client to server and in the server add (+1) with it and return back to client. Client print the line and send back to server the increased number until it reaches 10.
The connectivity between both classes is working properly, but when I put BufferedReader before PrintWriter in server class, then the application doesn't work and also doesn't throws any error.
Client Code:
int count = 1;
PrintWriter out = null;
BufferedReader in = null;
Socket socket = null;
try {
socket = new Socket("localhost",3700);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
while(in.read() != 10){
out.println(count);
out.flush();
System.out.print(in.read());
};
out.close();
in.close();
socket.close();
Server Code:
ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
int count = 1;
try {
serverSocket = new ServerSocket(3700);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
out = new PrintWriter(socket.getOutputStream());
out.println(count);
out.flush();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(in.read() != 10){
count = in.read();
count++;
};
in.close();
out.close();
serverSocket.close();
socket.close();
while(in.read() != 10){
count = in.read();
count++;
};
You are reading characters and throwing them away, and you are ignoring end of stream. It should be:
int ch;
while((ch = in.read()) !- -1 && ch != 10){
count = ch;
count++;
};
and similarly for the server side. The -1 test is the end of stream condition, which happens when the peer closes the connection.
But more probably you should be using readLine() and Integer.parseInt():
String line;
while ((line = in.readLine()) != null)
{
int value = Integer.parseInt(line);
// etc.
}

Android Socket Error- >libcore.io.IoBridge.connect(Iobridge.java.114)

In the below code i am just creating a socket to run the Shell command in my App but the problem is some times it runs and most of the time it through the error (libcore.io.IoBridge)
PrintWriter writer = null;
BufferedReader in = null;
String inputLine;
try {
Socket clientSocket = null;
clientSocket = new Socket(LOCAL_ADDRESS, PORT);
Log.d("ExecuteService", (clientSocket.isConnected() ? "Connected" : "Not Connected"));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())),true);
writer.println(cmd);
writer.flush();
Log.d("ExecuteService", "Lineis in:" + cmd);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d("ExecuteService", "Lines :" + inputLine);
}
Log.d("ExecuteService", "Lineis out:" + cmd);
writer.close();
writer = null;
in.close();
in = null;
clientSocket.close();
clientSocket = null;
} catch (Exception exception) {
for(StackTraceElement st : exception.getStackTrace())
Log.d("ExecuteService", st.toString());
}
}
Can any one please let me know how n when this error gets occur?

Why won't my statement send to client side?

I just want to send a simple string to the client side, however it is not doing so.
It will just skip the out.println statement and just do the rest of the program properly.
Is out.println the wrong statement for sending to the client from the server side?
I just want to send "hello" by using this code.
out.println("hello");
program for server side
public class TcpServerCompareCSV {
public static void main(String[] args) throws IOException{
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\Downloads\\orders.csv";
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(57634);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
Boolean comp;
while ((inputLine = in.readLine()) != null)
{
***out.println("hello");***
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
System.out.println ("Server: " + inputLine);
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
comp = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
if(comp)
out.println(noError);
else
out.println(Error);
input1.close();
input2.close();
input3.close();
input4.close();
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
program for client side
public class TcpClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("WA12345"); //127.0.0.1
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 57634.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// echoSocket = new Socket("taranis", 7);
echoSocket = new Socket(serverHostname, 57634);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.print ("input: ");
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye.")){
System.out.println("Exit program");
break;
}
getValueLog(parseFixMsg(userInput,userInput));
System.out.print ("input: ");
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
You are never reading from your socket input stream in your client program (created by statementin = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); ), so you never actually try to receive it.
You need a in.readLine() in your client program in the loop, after
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
It should look like this:
System.out.println(in.readLine());

Java two- way socket connection (server/ client)

what I'm trying to do is to send some JSON from an Android phone to a Java server, which works fine. The Android/ client side looks like this:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
s.close();
The server side is this:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
As I said, all of that works. Now I want to send a message back from the server to the client after it received the message from the client.
I extended the code like this, Android/ client side:
Socket s = new Socket("192.168.0.36", 12390);
s.setSoTimeout(1500);
JSONObject json = new JSONObject();
json.put("emergency", false);
json.put("imei", imei);
json.put("lat", l.getLatitude());
json.put("lon", l.getLongitude());
json.put("acc", l.getAccuracy());
json.put("time", l.getTime());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
s.getOutputStream()));
out.write(json.toString());
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
And the server side:
try {
s = new ServerSocket(port);
}
catch (IOException e) {
System.out.println("Could not listen on port: " + port);
System.exit(-1);
}
Socket c = null;
while (true) {
try {
c = s.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
try {
BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
String inputLine = null;
String result = "";
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
System.out.println(result);
PrintWriter out = new PrintWriter(c.getOutputStream());
out.write("Hello phone");
out.flush();
out.close();
On the client side, nothing ever comes in, it hangs on
while ((inputLine = in.readLine()) != null) {
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
until the socket times out (never enters the loop). I thought it might be a timing problem, for example the server sending out its reply too early and therefore the client never receiving anything, but i tried to put the out.write("Hello phone"); pretty much anywhere in the code, always the same result. Can it have to do with the socket being obtained from ServerSocket and not being able to send out data? What am I missing here, this is bugging me all day ...
Edit: After Nikolais answer, I tried this (client):
out.write(json.toString());
out.newLine();
out.write("###");
out.flush();
String inputLine = null;
String result = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("###")) {
break;
}
Log.d(TAG, in.readLine());
result = result.concat(inputLine);
}
s.close();
and server:
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
if (inputLine.contains("###")) {
System.out.println("received ###");
out.println("Hello phone");
out.println("###");
out.flush();
break;
}
}
The idea was to send out the message from the server before the client closes the socket. Still doesnt work ... any hints?
On the server side you never get to sending your "Hello phone". Not until client closes the socket, but at that point it's useless. This is because in.readLine() blocks until either data is available or EOF, i.e. socket closed.
You need a way to get out of the reading loop - invent (or adopt) some application-level protocol that would tell you that a whole message is received. Common options are fixed length messages, length prefix, delimited, etc.

Categories

Resources