Skip to content

Commit aac2dbd

Browse files
authored
Merge pull request #165 from DoYouEvenBacon/master
Add connection timeout for TCP
2 parents 2d3cfe0 + 5bac541 commit aac2dbd

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

escposprinter/src/main/java/com/dantsu/escposprinter/connection/tcp/TcpConnection.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
import java.net.InetAddress;
88
import java.net.InetSocketAddress;
99
import java.net.Socket;
10+
import java.net.SocketTimeoutException;
1011

1112
public class TcpConnection extends DeviceConnection {
1213
private Socket socket = null;
1314
private String address;
1415
private int port;
16+
private int timeout = 0;
1517

1618
/**
1719
* Create un instance of TcpConnection.
@@ -25,6 +27,23 @@ public TcpConnection(String address, int port) {
2527
this.port = port;
2628
}
2729

30+
/**
31+
* Create un instance of TcpConnection.
32+
*
33+
* Overload of the above function TcpConnection()
34+
* Include timeout parameter in milliseconds.
35+
*
36+
* @param address IP address of the device
37+
* @param port Port of the device
38+
* @param timeout Timeout in milliseconds to establish a connection
39+
*/
40+
public TcpConnection(String address, int port, int timeout) {
41+
super();
42+
this.address = address;
43+
this.port = port;
44+
this.timeout = timeout;
45+
}
46+
2847
/**
2948
* Check if the TCP device is connected by socket.
3049
*
@@ -43,13 +62,17 @@ public TcpConnection connect() throws EscPosConnectionException {
4362
}
4463
try {
4564
this.socket = new Socket();
46-
this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port));
65+
this.socket.connect(new InetSocketAddress(InetAddress.getByName(this.address), this.port), this.timeout); //https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#connect-java.net.SocketAddress-int- - A timeout of zero is interpreted as an infinite timeout
4766
this.outputStream = this.socket.getOutputStream();
4867
this.data = new byte[0];
4968
} catch (IOException e) {
5069
e.printStackTrace();
5170
this.disconnect();
5271
throw new EscPosConnectionException("Unable to connect to TCP device.");
72+
} catch (SocketTimeoutException e) {
73+
e.printStackTrace();
74+
this.disconnect();
75+
throw new EscPosConnectionException("Unable to connect to TCP device; exceeded timeout limit.");
5376
}
5477
return this;
5578
}

0 commit comments

Comments
 (0)