I am trying to code a printer server that acts as a relay server to receive and send connections from JPOS applications on network and relay them to a printer on the network.
I am using EPSON JPOS tools to test that since I have an EPSON receipt printer.
Using Java, right now I am able to receive and send UDP connections properly, but for TCP connections I cannot read anything from TCP server; because it almost instantly gives error "The port is already open" in JPOS application and seems to close connection with server.
Below is the code for TCP server socket:-
public class TcpListener {
private int sendReceiveBufferSize = 256;
public void listen(int port, int bufferSize) throws Exception {
System.out.println("-- Running TCP Server at " + InetAddress.getLocalHost() + ":" + port + " --");
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket jposSocket = null;
InputStream inJpos = null;
OutputStream outJpos = null;
ByteArrayOutputStream abOutputStream = null;
ByteArrayOutputStream abJposOutputStream = null;
try {
jposSocket = serverSocket.accept();
jposSocket.setSoTimeout(5000);
jposSocket.setReceiveBufferSize(sendReceiveBufferSize);
jposSocket.setSendBufferSize(sendReceiveBufferSize);
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
inJpos = jposSocket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
outJpos = jposSocket.getOutputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
abOutputStream = null;
abJposOutputStream = new ByteArrayOutputStream();
Socket printerSocket = null;
InputStream inPrinter = null;
OutputStream outPrinter = null;
int count = 0;
while (true)
{
abOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[bufferSize];
//count = inJpos.read(bytes);
while (true) {
if (inJpos.available() > 0)
{
count = inJpos.read(bytes);
abOutputStream.write(bytes, 0, count);
break;
}
else {
Thread.sleep(1000);
}
}
System.out.println(port + " TCP --> " + abOutputStream.toString("UTF-8"));
if (printerSocket == null)
{
printerSocket = new Socket("192.168.10.31", port);
inPrinter = printerSocket.getInputStream();
outPrinter = printerSocket.getOutputStream();
}
outPrinter.write(abOutputStream.toByteArray());
bytes = new byte[bufferSize];
while (inPrinter.available() > 0 && (count = inPrinter.read(bytes)) > 0) {
abJposOutputStream.write(bytes, 0, count);
}
outJpos.write(abJposOutputStream.toByteArray());
outJpos.flush();
}
}
}
Then Listen method is called from Main application on a sperate thread.
Above code works fine when tested with a client that I wrote, it sends and receives messages properly, but the issue is with JPOS connection.
Is there some kind of special handling for TCP connections from JPOS applications or what?
Any help would be appreciated.
Thanks