我有一个服务器应用程序,它可能会同时接收来自多个客户端的传入连接。它用于从 Internet 接收数据并将其发送到本地的 POS 打印机。这是代码:
public static void main(String args[]) {
RFServer2 server = new RFServer2();
while (true) {
server.run();
}
}
public RFServer2() {
}
public synchronized void run() {
try {
while (printing)
wait();
printing = true;
// 1. creating a server socket
providerSocket = new ServerSocket(43520);
// 2. Wait for connection
System.out.println("Waiting connection...");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
connection.setSoTimeout(8000);
// 3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
try {
in = new ObjectInputStream(connection.getInputStream());
} catch (Exception e) {
throw new Exception("Weird connection received, could not read, aborting...");
}
// sendMessage("connected");
// 4. The two parts communicate via the input and output streams
try {
message = (String) in.readObject();
if (message.contains(".")) {
Socket printerSocket = new Socket(message, 9100);
printerSocket.setSoTimeout(3000);
printer = printerSocket.getOutputStream();
printer.flush();
sendMessage("connected");
while (!message.contentEquals("done")) {
try {
message = (String) in.readObject();
if (!message.contentEquals("done")) {
printer.write(message.getBytes("UTF-8"));
printer.flush();
}
} catch (Exception e) {
System.err.println("Failed to print.");
e.printStackTrace();
break;
}
}
this.message = "";
catch (Exception e) {
System.err.println(e.getMessage());
} finally {
// 5: Closing connection
try {
this.message = "";
if (printer != null) {
System.out.println("Closing connection to the printer...");
printer.close();
}
if (in != null) {
System.out.println("Closing input...");
in.close();
}
if (out != null) {
System.out.println("Closing output...");
out.close();
}
System.out.println(new Date() + " - letting server listening...");
if (providerSocket != null)
providerSocket.close();
printing = false;
notify();
} catch (Exception ioException) {
ioException.printStackTrace();
}
}
}
好吧,如果我从同一个客户端(例如我的机器)发送多个连接,应用程序会使用 wait() 和 notify() 处理线程,同步它们。但是,如果我同时从 2 台不同的计算机发送 2 个连接,我的服务器会卡在“从主机收到连接”,并且两个客户端由于超时而掉线。
我所需要的只是解决这个小问题......我已经阅读了这些主题,但未能成功解决我的问题