What's causing my SocketException: Connection reset? - java

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

Related

Client not able to receive messages from Server Socket programming 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);

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?

Writing a file to another file

When I tried to run OUT.TXT it was alwasy empty. Can you please assist me in finding out why? Also SPY.LOG lines are not ordinary, can you assit with a way to fix those lines also?
package burak;
import java.io.*;
public class Yucal {
public static void main(String [] args) {
String fileName = "spy.log";
String line;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(line);
out.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'"); }
}
Few changes
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
while ((line = bufferedReader.readLine()) != null) {
try {
out.write(line);
out.write("\n");
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.printf("%65s\n", line);
}
out.close();
bufferedReader.close();
The mistake was you've opened FileWriter fstream = new FileWriter("out.txt"); within while loop. It must be outside.
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
try{
>FileWriter fstream = new FileWriter("out.txt");**
>BufferedWriter out = new BufferedWriter(fstream);**
<snip>
Everytime you open your file and write one line. Then close it. Next time you open it, you overwrite the previous contents of the file. You should probably move the lines marked with > outside the while loop.
The last line of your file spy.log might be empty.
Additionally move all close statements to finally block.
You might also need to handler some IO exceptions when you close these streams.
Hope this helps.

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