У меня есть небольшой примитивный сервер для изучения и на стороне клиента.
Здесь у меня есть часть моего кода сервера:
public class Connector implements Runnable, SocketListener {
private Socket socket;
private ServerSocket serverSocket;
private List<ServerSideClient> clients = new LinkedList<>();
private boolean triger;
public Connector(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
@Override
public void run() {
while (true) {
try {
System.out.println("Waiting for clients..");
triger = true;
socket = serverSocket.accept();
System.out.println("Client connected");
ServerSideClient client = createClient();
client.setConnection(true);
client.startListeningClient();
clients.add(client);
new Thread(() -> {
socketIsClosed(client);
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private ServerSideClient createClient() {
return new ServerSideClient(socket);
}
@Override
public synchronized void socketIsClosed(ServerSideClient client) {
while (triger == true) {
if (client.isConnected() == false) {
triger = false;
clients.remove(client);
System.out.println("Client was removed " + clients.size());
}
}
}
}
Здесь мы ждем нового Клиента, затем создаем экземпляр клиента и добавляем его в LinkedList. В случае со стороны сервера мы ожидаем информацию от клиента и отправляем ответ в отдельном потоке. Но когда клиент закрывает соединение с сервером, метод socketIsClosed()
должен удалить текущую ссылку клиента из коллекции. Но когда клиент отключен, у меня даже нет выхода System.out.println("Client was removed " + clients.size());
из socketIsClosed(ServerSideClient client)
метода.
Код клиента:
public class Client {
private final String HOST = "localhost";
private final int PORT = 1022;
private InputStream inputStream;
private OutputStream outputStream;
private BufferedReader bufferedReader;
private Socket socket;
private boolean connection;
public Client() throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(HOST, PORT));
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
Client client = null;
try {
client = new Client();
client.work();
} catch (IOException e) {
e.printStackTrace();
}
}
private void work() {
connection = true;
listenForConsoleInput();
receiveAnswerFromServer();
}
private void listenForConsoleInput() {
new Thread(() -> {
while (connection == true) {
String requset = null;
try {
requset = bufferedReader.readLine();
if (requset.equals(".")) {
closeConnection();
return;
} else {
sendRequest(requset);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void sendRequest(String request) {
try {
outputStream.write(request.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void receiveAnswerFromServer() {
new Thread(() -> {
while (connection == true) {
byte[] data = new byte[32 * 1024];
try {
int numberOfBytes = inputStream.read(data);
System.out.println("Server>> " + new String(data, 0, numberOfBytes));
} catch (IOException e) {
closeConnection();
}
}
}).start();
}
private void closeConnection() {
try {
connection = false;
socket.close();
inputStream.close();
outputStream.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
socketIsClosed(ServerSideClient client)
метод работает в отдельном потоке.
public class ServerSideClient {
private Socket socket;
private InputStream in;
private OutputStream out;
private boolean connection;
private int numOfBytes;
public boolean isConnected() {
return connection;
}
public void setConnection(boolean connection) {
this.connection = connection;
}
public ServerSideClient(Socket socket) {
this.socket = socket;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startListeningClient() {
new Thread(() -> {
listenUsers();
}).start();
}
private void listenUsers() {
while (connection == true) {
byte[] data = new byte[32 * 1024];
readInputFromClient(data);
if (numOfBytes == -1) {
try {
connection = false;
socket.close();
in.close();
out.close();
isConnected();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Client disconected..");
return;
}
String requestFromClient = new String(data, 0, numOfBytes);
System.out.println("Client sended>> " + requestFromClient);
sendResponce(requestFromClient);
}
}
private void readInputFromClient(byte[] data) {
try {
numOfBytes = in.read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendResponce(String resp) {
try {
out.write(resp.getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Я пытаюсь решить эту проблему с 2 недели, Helllllllp .....