Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.27 KB | None | 0 0
  1. /**
  2.  * @author Maziarz Mateusz S14112
  3.  */
  4.  
  5. package zad1;
  6.  
  7. import java.io.IOException;
  8. import java.net.InetSocketAddress;
  9. import java.nio.ByteBuffer;
  10. import java.nio.channels.*;
  11. import java.util.*;
  12.  
  13. public class Server{
  14.  
  15.     private static final int SERVER_PORT;
  16.     private static final String HOST_NAME;
  17.     private final Map<SocketChannel, StringBuilder> session;
  18.     public static final String END_MESSAGE_MARKER = ":END";
  19.     private static final int BUFFER_SIZE = 1024;
  20.     private Selector selector;
  21.  
  22.     static {
  23.         SERVER_PORT = 60000;
  24.         HOST_NAME = "127.0.0.1";
  25.     }
  26.  
  27.     public Server() {
  28.         session = new HashMap<>();
  29.         start();
  30.     }
  31.  
  32.     private void start() {
  33.         try {
  34.             ServerSocketChannel channel = ServerSocketChannel.open();
  35.             selector = Selector.open();
  36.             initializeChannel(channel, selector);
  37.  
  38.             while (!Thread.currentThread().isInterrupted()) {
  39.                 if (selector.isOpen()) {
  40.                     final int numKeys = selector.select();
  41.                     if (numKeys > 0) {
  42.                         handleKeys(channel, selector.selectedKeys(), selector);
  43.                     }
  44.                 } else {
  45.                     Thread.currentThread().interrupt();
  46.                 }
  47.             }
  48.         } catch (IOException e) {
  49.             throw new RuntimeException("Unable to start server.", e);
  50.         } finally {
  51.  
  52.         }
  53.     }
  54.  
  55.     private void handleKeys(final ServerSocketChannel channel, final Set<SelectionKey> keys, Selector selector) throws IOException {
  56.  
  57.         final Iterator<SelectionKey> iterator = keys.iterator();
  58.         while (iterator.hasNext()) {
  59.  
  60.             final SelectionKey key = iterator.next();
  61.             try {
  62.                 if (key.isValid()) {
  63.                     if (key.isAcceptable()) {
  64.                         acceptConnection(channel, key);
  65.                     } else if (key.isReadable()) {
  66.                         readMessage(key);
  67.                     } else {
  68.                         throw new UnsupportedOperationException("Key not supported by server.");
  69.                     }
  70.                 } else {
  71.                     throw new UnsupportedOperationException("Key not valid.");
  72.                 }
  73.             } finally {
  74.                 if (isMessageEnded(key)) {
  75.                     reSendMessages(key);
  76.                     cleanUp(key);
  77.                 }
  78.                 iterator.remove();
  79.             }
  80.         }
  81.     }
  82.  
  83.     private void initializeChannel(final ServerSocketChannel serverChannel, final Selector selector) {
  84.         try {
  85.             serverChannel.socket().setReuseAddress(true);
  86.             serverChannel.configureBlocking(false);
  87.             serverChannel.socket().bind(new InetSocketAddress(SERVER_PORT));
  88.             serverChannel.register(selector, SelectionKey.OP_ACCEPT);
  89.             System.out.println("Server is running");
  90.         } catch (IOException e) {
  91.             System.out.println("Blad przy inicjalizacji serwera");
  92.         }
  93.     }
  94.  
  95.     private void acceptConnection(final ServerSocketChannel serverChannel, final SelectionKey selectedKey){
  96.         try {
  97.             SocketChannel socketChannel = serverChannel.accept();
  98.             socketChannel.configureBlocking(false);
  99.             socketChannel.register(selectedKey.selector(), SelectionKey.OP_READ|SelectionKey.OP_WRITE );
  100.             this.session.put(socketChannel, new StringBuilder());
  101.         }catch (IOException e){
  102.             System.out.println("Blad przy akceptacji polaczenia");
  103.         }
  104.     }
  105.  
  106.     private boolean isMessageEnded(final SelectionKey selectedKey){
  107.         return (selectedKey.channel() instanceof SocketChannel) && this.session.get((SocketChannel) selectedKey.channel()).toString().contains(END_MESSAGE_MARKER);
  108.     }
  109.  
  110.     private void readMessage(final SelectionKey selectedKey){
  111.         final SocketChannel client = (SocketChannel) selectedKey.channel();
  112.         final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
  113.         try {
  114.             final int bytesRead = client.read(buffer);
  115.             if (bytesRead > 0) {
  116.                 this.session.get(client).append(new String(buffer.array()).trim());
  117.             }
  118.         }catch (IOException e){
  119.             System.out.println("Blad przy odczycie wiadomosci");
  120.         }
  121.     }
  122.  
  123.     private void reSendMessages(SelectionKey selectedKey) {
  124.         ByteBuffer buffer = ByteBuffer.wrap(this.session.get(selectedKey.channel()).toString().trim().getBytes());
  125.  
  126.             for (SelectionKey key : selector.keys()) {
  127.                 if (key.isValid() && key.channel() instanceof SocketChannel && key.isWritable()) {
  128.                     System.out.println("broadcast...");
  129.                     doWrite(buffer, (SocketChannel)key.channel());
  130.                     buffer.rewind();
  131.                 }
  132.             }
  133.         }
  134.  
  135.  
  136.     public void doWrite(final ByteBuffer buffer, final SocketChannel channel){
  137.         try {
  138.             while (buffer.hasRemaining()) {
  139.                 channel.write(buffer);
  140.             }
  141.         }catch (IOException e){
  142.             System.out.println("Blad zapisu wiadomosci do strumienia");
  143.         }
  144.     }
  145.  
  146.     private void cleanUp(final SelectionKey key) throws IOException {
  147.         key.channel().close();
  148.     }
  149. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement