Witam mam taki problem że serwer nie wie kiedy przestać wyświetlać IP na liście jak to zrobić?
Oto mój kod:
Klasa główna:
package common;
import client.Client;
import server.Server;
public class Main {
public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
public void run() {
try {
new Server(25565);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
new Client("localhost", 25565);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
Client c = new Client("localhost", 25565);
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Klasa Serwera:
package server;
import java.awt.Color;
import java.awt.Dimension;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Server extends ServerSocket {
ArrayList<Socket> sockets = new ArrayList<Socket>();
JFrame frame = new JFrame("Server");
JTextArea area = new JTextArea();
public Server(int port) throws Exception {
super(port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400, 500));
frame.pack();
frame.setLayout(null);
area.setSize(new Dimension(370, 450));
area.setBackground(Color.DARK_GRAY);
area.setForeground(Color.WHITE);
area.setLocation(10, 10);
frame.add(area);
frame.setVisible(true);
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
for(Socket so : sockets) {
if(!so.isConnected()) {
System.out.println("D");
sockets.remove(so);
}
}
String s = "";
for(Socket so : sockets) {
s = s + so.getRemoteSocketAddress().toString().replaceAll("/", "") + "\n";
}
area.setText(s);
}
}, 600, 600);
while(true) {
final Socket socket = accept();
sockets.add(socket);
new Thread(new Runnable() {
public void run() {
try {
String s = "";
for(Socket so : sockets) {
s = s + so.getRemoteSocketAddress().toString().replaceAll("/", "") + "\n";
}
area.setText(s);
} catch(Exception ex) {}
}
}).start();
}
}
}
Klasa Klienta:
package client;
import java.net.Socket;
public class Client extends Socket {
public Client(String host, int port) throws Exception {
super(host, port);
}
}