添加心跳保活逻辑

main v1.0.0
dai_48k 2024-01-24 17:15:20 +08:00
parent b092402eaf
commit 3a5a9aac44
2 changed files with 40 additions and 9 deletions

View File

@ -25,7 +25,7 @@ public class MainFrame extends JFrame {
System.out.println(now); System.out.println(now);
setTitle(now == Cross.BLACK ? "●" : "○"); setTitle(now == Cross.BLACK ? "●" : "○");
setSize(200,230 + BASE_HEIGHT); setSize(200,220 + BASE_HEIGHT);
addMouseListener(new MouseAdapter() { addMouseListener(new MouseAdapter() {
@Override @Override
@ -53,7 +53,7 @@ public class MainFrame extends JFrame {
try { try {
String o = (String) Client.recMsg(oi); String o = (String) Client.recMsg(oi);
if (o.startsWith("INFO:")) { if (o.startsWith("INFO:") || o.startsWith("WARN:")) {
tip = o; tip = o;
} else { } else {
map = DataUtil.rawData(o); map = DataUtil.rawData(o);
@ -72,7 +72,7 @@ public class MainFrame extends JFrame {
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
g.setColor(Color.white); g.setColor(Color.white);
g.fillRect(0,BASE_HEIGHT,200,230); g.fillRect(0,BASE_HEIGHT,200,220);
g.setColor(Color.lightGray); g.setColor(Color.lightGray);
for (int i = 1; i <= 9; i++) { for (int i = 1; i <= 9; i++) {
@ -90,7 +90,10 @@ public class MainFrame extends JFrame {
} }
} }
if(tip.contains("INFO")) g.setColor(Color.GREEN);
if(tip.contains("WARN")) g.setColor(Color.RED);
g.drawString(tip, BASE_FROM, 200 + BASE_HEIGHT); g.drawString(tip, BASE_FROM, 200 + BASE_HEIGHT);
g.setColor(Color.BLACK);
} }
@Override @Override

View File

@ -88,7 +88,7 @@ public class UserThread extends Thread{
} }
if (!allAlive || users.size() != 2) { if (!allAlive || users.size() != 2) {
sendMsg("INFO:对方未在线"); sendMsg("WARN:对方未在线");
} else { } else {
boolean result = CalDataUtil.draw(newClick, map); boolean result = CalDataUtil.draw(newClick, map);
if (result) { if (result) {
@ -108,13 +108,45 @@ public class UserThread extends Thread{
System.out.println("::" + e.getMessage()); System.out.println("::" + e.getMessage());
System.out.println("连接断开"); System.out.println("连接断开");
isAlive = false; isAlive = false;
break; break;
} }
} }
}); });
thread.start(); thread.start();
Thread heartBead = new Thread(() -> {
while (true){
if (users.size() == 2){
UserThread u1 = users.get(0);
UserThread u2 = users.get(1);
if (!u1.isAlive && !u2.isAlive) break;
if (!u1.isAlive) {
try {
u2.sendMsg("WARN: 对方已下线");
} catch (IOException e) {
break;
}
}
if (!u2.isAlive) {
try {
u1.sendMsg("WARN: 对方已下线");
} catch (IOException e) {
break;
}
}
}
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
break;
}
}
});
heartBead.start();
// 线程等待 // 线程等待
try { try {
thread.join(); thread.join();
@ -124,10 +156,6 @@ public class UserThread extends Thread{
} }
public Socket getSocket() {
return socket;
}
public void sendMsg(Object obj) throws IOException { public void sendMsg(Object obj) throws IOException {
os.writeObject(obj); os.writeObject(obj);
} }