Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @author Maziarz Mateusz S14112
- */
- package zad1;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.ByteBuffer;
- import java.nio.channels.*;
- import java.util.*;
- public class Server{
- private static final int SERVER_PORT;
- private static final String HOST_NAME;
- private final Map<SocketChannel, StringBuilder> session;
- public static final String END_MESSAGE_MARKER = ":END";
- private static final int BUFFER_SIZE = 1024;
- private Selector selector;
- static {
- SERVER_PORT = 60000;
- HOST_NAME = "127.0.0.1";
- }
- public Server() {
- session = new HashMap<>();
- start();
- }
- private void start() {
- try {
- ServerSocketChannel channel = ServerSocketChannel.open();
- selector = Selector.open();
- initializeChannel(channel, selector);
- while (!Thread.currentThread().isInterrupted()) {
- if (selector.isOpen()) {
- final int numKeys = selector.select();
- if (numKeys > 0) {
- handleKeys(channel, selector.selectedKeys(), selector);
- }
- } else {
- Thread.currentThread().interrupt();
- }
- }
- } catch (IOException e) {
- throw new RuntimeException("Unable to start server.", e);
- } finally {
- }
- }
- private void handleKeys(final ServerSocketChannel channel, final Set<SelectionKey> keys, Selector selector) throws IOException {
- final Iterator<SelectionKey> iterator = keys.iterator();
- while (iterator.hasNext()) {
- final SelectionKey key = iterator.next();
- try {
- if (key.isValid()) {
- if (key.isAcceptable()) {
- acceptConnection(channel, key);
- } else if (key.isReadable()) {
- readMessage(key);
- } else {
- throw new UnsupportedOperationException("Key not supported by server.");
- }
- } else {
- throw new UnsupportedOperationException("Key not valid.");
- }
- } finally {
- if (isMessageEnded(key)) {
- reSendMessages(key);
- cleanUp(key);
- }
- iterator.remove();
- }
- }
- }
- private void initializeChannel(final ServerSocketChannel serverChannel, final Selector selector) {
- try {
- serverChannel.socket().setReuseAddress(true);
- serverChannel.configureBlocking(false);
- serverChannel.socket().bind(new InetSocketAddress(SERVER_PORT));
- serverChannel.register(selector, SelectionKey.OP_ACCEPT);
- System.out.println("Server is running");
- } catch (IOException e) {
- System.out.println("Blad przy inicjalizacji serwera");
- }
- }
- private void acceptConnection(final ServerSocketChannel serverChannel, final SelectionKey selectedKey){
- try {
- SocketChannel socketChannel = serverChannel.accept();
- socketChannel.configureBlocking(false);
- socketChannel.register(selectedKey.selector(), SelectionKey.OP_READ|SelectionKey.OP_WRITE );
- this.session.put(socketChannel, new StringBuilder());
- }catch (IOException e){
- System.out.println("Blad przy akceptacji polaczenia");
- }
- }
- private boolean isMessageEnded(final SelectionKey selectedKey){
- return (selectedKey.channel() instanceof SocketChannel) && this.session.get((SocketChannel) selectedKey.channel()).toString().contains(END_MESSAGE_MARKER);
- }
- private void readMessage(final SelectionKey selectedKey){
- final SocketChannel client = (SocketChannel) selectedKey.channel();
- final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
- try {
- final int bytesRead = client.read(buffer);
- if (bytesRead > 0) {
- this.session.get(client).append(new String(buffer.array()).trim());
- }
- }catch (IOException e){
- System.out.println("Blad przy odczycie wiadomosci");
- }
- }
- private void reSendMessages(SelectionKey selectedKey) {
- ByteBuffer buffer = ByteBuffer.wrap(this.session.get(selectedKey.channel()).toString().trim().getBytes());
- for (SelectionKey key : selector.keys()) {
- if (key.isValid() && key.channel() instanceof SocketChannel && key.isWritable()) {
- System.out.println("broadcast...");
- doWrite(buffer, (SocketChannel)key.channel());
- buffer.rewind();
- }
- }
- }
- public void doWrite(final ByteBuffer buffer, final SocketChannel channel){
- try {
- while (buffer.hasRemaining()) {
- channel.write(buffer);
- }
- }catch (IOException e){
- System.out.println("Blad zapisu wiadomosci do strumienia");
- }
- }
- private void cleanUp(final SelectionKey key) throws IOException {
- key.channel().close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement