Skip to content

Commit

Permalink
Merge pull request #29 from andilem/master
Browse files Browse the repository at this point in the history
TCP parameter connectionTimeout + Close socket properly in case of Exception
  • Loading branch information
kochedykov authored Sep 23, 2018
2 parents 27eca82 + 9f67c26 commit 2abc6ed
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,20 @@ public ModbusTransport getTransport() {
protected void openImpl() throws ModbusIOException {
if (!isOpened()) {
if (parameters != null) {
Socket socket = new Socket();
InetSocketAddress isa = new InetSocketAddress(parameters.getHost(), parameters.getPort());
Socket socket = new Socket();
try {
socket.connect(isa, Modbus.MAX_CONNECTION_TIMEOUT);
socket.connect(isa, parameters.getConnectionTimeout());
socket.setKeepAlive(parameters.isKeepAlive());

transport = ModbusTransportFactory.createTCP(socket);
setReadTimeout(getReadTimeout());
} catch (Exception e) {
try {
socket.close();
} catch (IOException e1) {
// ignored
}
throw new ModbusIOException(e);
}
} else {
Expand Down
10 changes: 10 additions & 0 deletions src/com/intelligt/modbus/jlibmodbus/tcp/TcpParameters.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public class TcpParameters {
private InetAddress host = null;
private int port;
private boolean keepAlive;
private int connectionTimeout = Modbus.MAX_CONNECTION_TIMEOUT;

public TcpParameters() {
try {
Expand All @@ -43,6 +44,7 @@ public TcpParameters() {

public TcpParameters(TcpParameters p) {
this(p.getHost(), p.getPort(), p.isKeepAlive());
setConnectionTimeout(p.getConnectionTimeout());
}

public TcpParameters(InetAddress host, int port, boolean keepAlive) {
Expand Down Expand Up @@ -84,4 +86,12 @@ public boolean isKeepAlive() {
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}

public int getConnectionTimeout() {
return connectionTimeout;
}

public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
}

0 comments on commit 2abc6ed

Please sign in to comment.