我试图编码一个打印机服务器,作为中继服务器接收和发送网络上jpos应用程序的连接,并将它们中继到网络上的打印机。
我使用爱普生jpos工具来测试,因为我有一个爱普生收据打印机。
使用java,现在我能够正确地接收和发送udp连接,但是对于tcp连接,我不能从tcp服务器读取任何内容;因为它几乎立即在jpos应用程序中发出错误“端口已打开”,并且似乎关闭了与服务器的连接。
下面是tcp服务器的代码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();
}
}
}
然后从sperate线程上的主应用程序调用listen方法。
上面的代码在使用我编写的客户机进行测试时运行良好,它正确地发送和接收消息,但问题在于jpos连接。
对于来自jpos应用程序的tcp连接有什么特殊的处理吗?
任何帮助都将不胜感激。
谢谢
暂无答案!
目前还没有任何答案,快来回答吧!