Package eu.olol.jrc.server

Source Code of eu.olol.jrc.server.Server

package eu.olol.jrc.server;

import eu.olol.jrc.util.Control;
import eu.olol.jrc.util.Message;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

public class Server implements Observer, Runnable {

    ArrayList<ClientHandler> peers;
    HashMap<String, Channel> channels;
    ServerSocket socket;

    public Server(Integer port) throws IOException {
        peers = new ArrayList<>();
        channels = new HashMap<>();
        socket = new ServerSocket(port);
    }

    @Override
    public void update(Observable o, Object arg) {
        if (arg instanceof Message) {
            Message p = (Message) arg;

            // Send the post to the users in the channel
            for (Integer peerId : channels.get(p.getChannel()).getUsers()) {
                peers.get(peerId).send(p);
            }
        } else if (arg instanceof Control) {
            handleControl((ClientHandler) o, (Control) arg);
        }
    }

    private void handleControl(ClientHandler peer, Control control) {
        // Authenticate user
        // Change user nickname
    }

    @Override
    public void run() {
        try {
            while (true) {
                Socket clientSocket = socket.accept();
                Thread t = new Thread(new ClientHandler(clientSocket, this));
                t.start();
                System.out.println("Got a connection from " + clientSocket.getInetAddress() + ':' + clientSocket.getPort());
            }
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}
TOP

Related Classes of eu.olol.jrc.server.Server

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.