我正在尝试编写一个充当中继服务器的打印机服务器,以从网络上的 JPOS 应用程序接收和发送连接,并将它们中继到网络上的打印机。
我正在使用 EPSON JPOS 工具进行测试,因为我有一台 EPSON 收据打印机。
使用 Java,现在我能够正确接收和发送 UDP 连接,但是对于 TCP 连接,我无法从 TCP 服务器读取任何内容;因为它几乎立即在 JPOS 应用程序中给出错误“端口已打开”,并且似乎关闭了与服务器的连接。
以下是 TCP 服务器套接字的代码:-
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();
}
}
}
然后在一个单独的线程上从 Main 应用程序调用 Listen 方法。
上面的代码在使用我编写的客户端进行测试时工作正常,它可以正确发送和接收消息,但问题在于 JPOS 连接。
对来自 JPOS 应用程序的 TCP 连接是否有某种特殊处理?
任何帮助,将不胜感激。
谢谢