T
T
thatmaniscool2018-07-19 09:17:58
Java
thatmaniscool, 2018-07-19 09:17:58

Incorrect data transfer from the device to the server, how to fix it?

So, I am writing a simple server using the standard java.nio library.
The following problems arose:
1) The buffer is not cleaned at all. Those. information remains, which makes the application impossible.
2) The server will be lightly loaded, to control the smart home system. Because The server has only one physical port for connection to external periphery. Then the question arises, how can you limit the class responsible for communication to several clients?
3) When the client disconnects from the server. The server starts chaotically outputting data from the buffer. Those. behaves as if the client never disconnected and prints information from the buffer over and over again.
The code itself:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

public class Server {
  public static void main (String [] args) throws IOException{
    Selector selector = Selector.open(); // Открываем селектор.
    ServerSocketChannel serverSocket = ServerSocketChannel.open(); // Открываем канал.
    serverSocket.bind(new InetSocketAddress(4321)); // Связываем розетку с данным айпи и портом.
    serverSocket.configureBlocking(false); // Переводим в не блокировочный режим.
    serverSocket.register(selector, SelectionKey.OP_ACCEPT); // регистрируем селектор и устанавливливаем в режим  ожидание клиента.
    ByteBuffer buffer = ByteBuffer.allocate(256); // Выделяем 256 байт под буффер.
    
    
    while (true) {
      selector.select(); // Создаем список.
      Set <SelectionKey> selectedKey = selector.selectedKeys(); // Передаем список ключей.
      
      Iterator <SelectionKey> iter = selectedKey.iterator();  // создаем итератор.
      
      while (iter.hasNext()) {
        SelectionKey key  = iter.next(); // Получаем ключ к каналу.
        
        if (key.isAcceptable()) {
          register(selector, serverSocket);
        }
        
        if (key.isReadable()) {
          reader (buffer, key);
        }
        
        iter.remove();
      }
    }
    
  }
  
  
  private static void register (final Selector selector, final ServerSocketChannel serverSocket) throws IOException {
    assert !Objects.isNull(selector) && !Objects.isNull(serverSocket);
    SocketChannel client = serverSocket.accept(); // Подключаем нового пользователя.
    client.configureBlocking(false); // Переводим в блокировочный режим.
    client.register(selector, SelectionKey.OP_READ); // Регестрируем клиента, режим чтения.
  }
  
  private static void reader (final ByteBuffer buffer, final SelectionKey key) throws IOException {
    assert !Objects.isNull(buffer) && Objects.isNull(key);
    SocketChannel client = (SocketChannel) key.channel(); // Получаем канал.
    client.read(buffer); // Записываем значение в буффер.
    
    String messageFromClient = new String(buffer.array()).trim();
    System.out.println(messageFromClient);
    
    buffer.flip();
    client.write(buffer);
    buffer.clear();
  }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question