Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.DataOutputStream;
- import java.io.InputStreamReader;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.ArrayList;
- import java.io.IOException;
- enum MessageType {
- MESSAGE, DISCONNECT, GETCLIENTS
- };
- public class SecureServer {
- ServerSocket sSocket;
- ArrayList<SecureClientHandler> clientList = new ArrayList<SecureClientHandler>();
- /**
- * Starts the server. Should only be called once.
- * @param args Currently unused.
- */
- public static void main ( String[] args ) {
- SecureServer server = new SecureServer(7007);
- server.start();
- }
- /**
- * Constructor for the main server class.
- * @param port The port on which the ServerSocket will be listening
- */
- public SecureServer(int port) {
- try {
- sSocket = new ServerSocket(port);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * This runs the server loop. Not sure if this class should also extend Thread or implement Runnable to change this into a run() method
- */
- public void start() {
- while (true) {
- Socket client = null;
- try {
- client = sSocket.accept();
- } catch ( IOException e) {
- e.printStackTrace();
- }
- SecureClientHandler secureClient = new SecureClientHandler(client,this);
- clientList.add(secureClient);
- try {
- secureClient.run();
- } catch(Exception e) {
- System.out.println(e.getStackTrace());
- }
- }
- }
- /**
- * Returns a list of client descriptors that include information about the nickname (will later be stored in a database) or
- * the InetAddress of the client
- * @return List of clients
- */
- public ArrayList<InetAddress> getClients() {
- ArrayList<InetAddress> clients = new ArrayList<InetAddress>();
- for (SecureClientHandler s : clientList) {
- clients.add(s.getSocket().getInetAddress());
- }
- return clients;
- }
- /**
- * Resolves an InetAddress to the SecureClientHandler that holds the socket connection to that address
- * @param address The InetAddress to resolve
- * @return A SecureClientHandler instance that fits with the address
- */
- public SecureClientHandler resolveClientHandler(InetAddress address) throws ClientNotFoundException {
- for (SecureClientHandler h : clientList) {
- if ( address.equals(h.getSocket().getInetAddress() ) ) {
- return h;
- }
- }
- throw new ClientNotFoundException("Address could not be resolved to a currently available client");
- }
- public void disconnect(SecureClientHandler client, MessageType reason) {
- try {
- client.sendMessage(new SecureMessage("",MessageType.DISCONNECT,InetAddress.getByName("127.0.0.1"),InetAddress.getLocalHost()));
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment