aspose file tools*
The moose likes Threads and Synchronization and the fly likes  java.net.SocketException: Connection reset Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark " java.net.SocketException: Connection reset" Watch " java.net.SocketException: Connection reset" New topic
Author

java.net.SocketException: Connection reset

mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Hi everyone,

I'm new at socket programming and threads. I'd be happy if anyone can help me out with this exception.

In the main() I constructed the thread and then run it:

TransferServer _transferThread = new TransferServer(variableFilter.getExpression(),simu lationStopTime.getExpression());
_transferThread.run();

public class TransferServer extends Thread {
/** Construct Transfer Server thread by creating Transfer Server object and setting IP/port of the Server.
* @param toServer An output stream to send the request from Control Client to Control Server.
* @param inFromControlServer Set up an input stream to receive the response/simulation result back from the control server.
* @throws IOException If I/O error occurs while creating the socket.
*/
public TransferServer(String parameterFilter, String stopTime)
throws IOException {
_stopTime = stopTime;
_parameterFilter = parameterFilter;
_omcLogger = OMCLogger.getInstance();
_controlClient = new Socket("localhost", 10501);
// Set up an output stream to send request/operation to Control Server.
_toServer = new BufferedWriter(new OutputStreamWriter(
_controlClient.getOutputStream()));
_controlServer = new ServerSocket(10500);
String _controlRequest = "setcontrolclienturl#1#127.0.0.1#10500#end";
// Set the protocol of Control Server.
if (_controlRequest != null) {
_toServer.write(_controlRequest);
_toServer.flush();
}
Socket _controlConnection = _controlServer.accept();
// Set up an input stream to receive the response/simulation result back from Control Server.
_inFromControlServer = new BufferedReader(new InputStreamReader(
_controlConnection.getInputStream()));
_transferServer = new ServerSocket(10502);
String _transferRequest = "settransferclienturl#2#127.0.0.1#10502#end";
if (_transferRequest != null) {
_toServer.write(_transferRequest);
_toServer.flush();
}
Socket _transferConnection = _transferServer.accept();
_inFromTransferServer = new BufferedReader(new InputStreamReader(
_transferConnection.getInputStream()));
if (_controlClient.isConnected() && _toServer != null) {
try {
String parameterSequence = _parameterFilter;
String[] parameters = null;
String parameterDelimiter = "#";
parameters = parameterSequence.split(parameterDelimiter);
if (parameters.length >= 2) {
_toServer
.write("setfilter#3#" + parameterSequence + "#end");
_toServer.flush();
} else if (parameters.length == 1) {
_toServer.write("setfilter#3#" + parameters[0] + "#end");
_toServer.flush();
} else
System.err.println("Filter cannot be set!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_toServer.write("start#4#end");
_toServer.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_toServer.write("shutdown#5#end");
_toServer.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
throw new IOException("!" + e.getMessage());
}
char[] controlServerBuffer = new char[124];
String statusMessage = null;
try {
_inFromControlServer.read(controlServerBuffer);
statusMessage = new String(controlServerBuffer).trim();
} catch (IOException e) {
e.printStackTrace();
throw new IOException("!" + e.getMessage());
}
String loggerInfo = "Status Message from Control Server for setting transfer and control client url: ";
statusMessage = new String(controlServerBuffer).trim();
if (statusMessage != null) {
loggerInfo = "Status Message from Transfer Server : "
+ statusMessage;
_omcLogger.getInfo(loggerInfo);
}
}
}
public void run() {
// Read simulation result from Transfer Server, then write them to the console.
String lineDelimiter = "end";
String timeDelimiter = "#";
String[] lineSplitResult = null;
String[] timeSplitResult = null;
String[] recordResult = null;
String wholeSimulationResult = null;
String lineSimulationResult = null;
int streamIndex = 0;
char[] transferServerBuffer = new char[1024];
RecordToken record = null;
// It returns -1 if the end of the stream is reached.
// If not, it returns the number of chars that have been read.
if (_transferServer.isBound()) {
Outerloop: try {
while ((streamIndex = _inFromTransferServer
.read(transferServerBuffer)) != -1) {
wholeSimulationResult = new String(transferServerBuffer)
.trim();
lineSplitResult = wholeSimulationResult
.split(lineDelimiter);
for (int i = 0; i < lineSplitResult.length - 1; i++) {
lineSimulationResult = lineSplitResult[i];
timeSplitResult = lineSimulationResult
.split(timeDelimiter);
for (int j = 1; j < timeSplitResult.length; j++) {
if (j == 1) {
if ((timeSplitResult[j].toString()
.startsWith(_stopTime)))
break Outerloop;
else
System.out.print("At time : "
+ timeSplitResult[j] + " ");
} else {
System.out.print(timeSplitResult[j] + " ");
}
}
}
}
System.out.println("Stop time is reached!");
} catch (IOException e) {
e.printStackTrace();
}
try {
_controlClient.close();
_controlServer.close();
_toServer.close();
_inFromControlServer.close();
// Stop the thread and close the server socket.
stopExecuting();
String loggerInfo = "Socket Closed!";
_omcLogger.getInfo(loggerInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////////////////////
//// private variables ////
// Control client socket.
private Socket _controlClient = null;
// Control server socket.
private ServerSocket _controlServer = null;
// Set up an input stream to receive the response/simulation result back from the control server.
private BufferedReader _inFromControlServer = null;
// An input stream to receive the simulation result back from Transfer Server.
private BufferedReader _inFromTransferServer = null;
// OMCLogger Object for accessing a unique source of instance.
private OMCLogger _omcLogger = null;
//
private String _parameterFilter = null;
// Stop time of model simulation.
private String _stopTime = null;
// Set up an output stream to send the request/operation from control client to the server.
private BufferedWriter _toServer = null;
// Transfer Server.
private ServerSocket _transferServer = null;
}
That's the stacktrace of the exception:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream. java:196)
at java.net.SocketInputStream.read(SocketInputStream. java:122)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.j ava:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.ja va:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:1 77)
at java.io.InputStreamReader.read(InputStreamReader.j ava:184)
at java.io.BufferedReader.fill(BufferedReader.java:15 4)
at java.io.BufferedReader.read1(BufferedReader.java:2 05)
at java.io.BufferedReader.read(BufferedReader.java:27 9)
at java.io.Reader.read(Reader.java:140)
at ptolemy.domains.openmodelica.lib.omc.TransferServe r.run(TransferServer.java:216)
at ptolemy.domains.openmodelica.lib.OpenModelica.fire (OpenModelica.java:466)
at ptolemy.actor.sched.FixedPointDirector._fireActor( FixedPointDirector.java:808)
at ptolemy.actor.sched.FixedPointDirector.fire(FixedP ointDirector.java:241)
at ptolemy.domains.continuous.kernel.ContinuousDirect or.fire(ContinuousDirector.java:448)
at ptolemy.actor.CompositeActor.fire(CompositeActor.j ava:450)
at ptolemy.actor.CompositeActor.iterate(CompositeActo r.java:1089)
at ptolemy.actor.sched.StaticSchedulingDirector.fire( StaticSchedulingDirector.java:210)
at ptolemy.domains.sdf.kernel.SDFDirector.fire(SDFDir ector.java:492)
at ptolemy.actor.CompositeActor.fire(CompositeActor.j ava:450)
at ptolemy.actor.Manager.iterate(Manager.java:787)
at ptolemy.actor.Manager.execute(Manager.java:352)
at ptolemy.actor.Manager.run(Manager.java:1202)
at ptolemy.actor.Manager$PtolemyRunThread.run(Manager .java:1760)

Thanks
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
Your stack trace is pointing to line 216 of TransferServer as the first point it has a problem. What's going on at that point in your code?

(Edited to say) Also, use the "code" tags when you post your programs. It makes it easier to read. I'm not a really a greenhorn. I changed emails and lost my old login. I've found the ranch (all engineering forums in fact) to be very particular about what questions will be responded to (kindly - ha) and what format to post your questions in. Not that I'm any expert, but there's actually a good resource for how to ask good questions on forums written by a developer. I'm sure Google will be your friend there.
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:Your stack trace is pointing to line 216 of TransferServer as the first point it has a problem. What's going on at that point in your code?


line 216 : while ((streamIndex = _inFromTransferServer.read(transferServerBuffer)) != -1) : it's reading the result from server
when I debug the code exactly at this point the socketexception is thrown.
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
If you're getting socket exception there, is it possible your Connection is closed?
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
I see where you've got that socket running on several different ports and this one is failing on 10502. What does your client socket that is binding to that port look like? Your connection was reset (see first line of stack trace). That can be because you closed the connection.
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:If you're getting socket exception there, is it possible your Connection is closed?


First I check the connection if(_transferServer.isBound()) then the result is read from server, this condition return true.
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:I see where you've got that socket running on several different ports and this one is failing on 10502. What does your client socket that is binding to that port look like? Your connection was reset (see first line of stack trace). That can be because you closed the connection.

That's client socket : _controlClient = new Socket("localhost", 10501);
Closing the socket is done in the last try catch after reading the result
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
isBound() does not report on whether a Connection is alive or not. The socket binds to ports, not connections. You want to use another method to check...
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:isBound() does not report on whether a Connection is alive or not. The socket binds to ports, not connections. You want to use another method to check...


what method do you suggest to use?
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
Have you looked at isClosed() or isConnected() from the API? I don't ever use those methods as my read stream tells me what I need to know and catching sudden disconnects will fail gracefully. But to just get the connection established and see where it is failing these methods may help you : Javadoc Sockets
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:Have you looked at isClosed() or isConnected() from the API? I don't ever use those methods as my read stream tells me what I need to know and catching sudden disconnects will fail gracefully. But to just get the connection established and see where it is failing these methods may help you : Javadoc Sockets


I checked this condition: (!(_transferServer.isClosed()) && _controlClient.isConnected() &&!(_controlServer.isClosed()) :
both server sockets are opened and the client socket is connected.
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
You may have a client connection, but not an InputStream or OutputStream due to the client (perhaps) having closed it. I have also gotten security exceptions in the past although I would expect your stack trace to report something else if that were the case and all your other sockets would fail too. Speaking of, do you get any results from any socket you read or write to other than errors? Also, have you checked your client socket to make sure that the OutputStream is not closed before your server's InputStream is done reading (or ready to read)?

I use a the ExecutorService for my threads other than for the server thread which starts and runs independent from the thread pool. Here's an example of my latest working SocketServer :




Now the client which I connect to the socket and read from :



Finally, here is how I write to the client.



While you'll need to cut out the pieces and parts that are relevant to you, the program I describe works currently and I never get connection reset errors. Your connection must be closed.

You should also consider breaking up your code a lot more. Some developers can help you rapidly but I have a hard time following along with a long set of inline instructions. Other than that, I would post the client code separately so that it will be easier to tell if that is what is closing your Stream.
Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
BTW, it looks like you've got a ServerSocket running at 10502 and a Socket running at port 10501. You have another ServerSocket running at 10500. Where is your server running at port 10501?
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Sorry Alvin for not breaking up my code and it took your time to figure it out:

That's the main():


That's the thread class:
mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
Alvin Parker wrote:BTW, it looks like you've got a ServerSocket running at 10502 and a Socket running at port 10501. You have another ServerSocket running at 10500. Where is your server running at port 10501?


Yes, two server sockets are running,
1) Control Server at port 10500, I have no problem in getting result from this server it returns "done#1#end#done#2#end#done#3#end#done#4#end#done#5#end"
2) Transfer Server at port 10502, the socket exception occurs at the time of reading result from Transfer server - line 103.

Client Socket is running at localhost/10501 :



And thanks for your example I'm trying to figure out how I should solve this exception.

mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
I set up the condition to check if the inputstream ,_inFromTransferServer, for reading the result from the server is ready or not, at line 92-FIXME, it returns false.
That's the reason connection is reset?

mania mir
Greenhorn

Joined: Oct 08, 2013
Posts: 11
In the last code snippet, at line 67 the result from ControlServer is read successfully and there is no exception.

mania mir wrote:
Alvin Parker wrote:BTW, it looks like you've got a ServerSocket running at 10502 and a Socket running at port 10501. You have another ServerSocket running at 10500. Where is your server running at port 10501?


Yes, two server sockets are running,
1) Control Server at port 10500, I have no problem in getting result from this server it returns "done#1#end#done#2#end#done#3#end#done#4#end#done#5#end"
2) Transfer Server at port 10502, the socket exception occurs at the time of reading result from Transfer server - line 103.

Client Socket is running at localhost/10501 :



And thanks for your example I'm trying to figure out how I should solve this exception.

Alvin Parker
Ranch Hand

Joined: Oct 01, 2013
Posts: 38
You are creating a client before any of your servers are open - and connecting. Moreover, your client does not talk to your servers. It talks on a different port than either of your servers so I'm not sure how you can get any results (if this is all of your code).

You need to start your server (ServerSocket) first and make sure it is running (move all your server code to a different object and all your client code to yet another object). Once it is running, then you call it with a client (Socket) at the port it is running at. So, if your server is running at 10501, you need your client to connect to port 10501 in a different object.

The Java trail has a good tutorial on Sockets. Java Sockets

(Edited to say) I see now how you're getting results. You are simply having your ServerSocket call a scoped reference to your client Socket which has data written to it because you wrote the data in that object. It can get the streams it needs because they are there but you're not actually connecting to and writing across a Socket.
 
 
subject: java.net.SocketException: Connection reset