package chatrooms; import java.io.IOException; import java.net.InetSocketAddress; import java.net.StandardSocketOptions; import java.nio.channels.ClosedChannelException; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.Map; import csc4509.HalfDuplexMsgWorker; import csc4509.ReadMessageStatus; public class ChatRoomServerHandShake { static boolean debug = true; static Map theWorkers = new HashMap(); static ChatRoomServer theChat; static int workerPort; public static void main(String[] argv) { ServerSocketChannel listenChannel; if (argv.length != 1) { System.out.println("usage: java ChatRoomServerMain "); return; } int startPort = Integer.parseInt(argv[0]); workerPort = startPort+100; ReadMessageStatus status; SocketChannel rwChan; // creates the selector and the listener try { listenChannel = ServerSocketChannel.open(); listenChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); listenChannel.bind(new InetSocketAddress(startPort)); while (true) { rwChan = listenChannel.accept(); HalfDuplexMsgWorker clientLink = new HalfDuplexMsgWorker(rwChan); rwChan = null; if (debug) { System.out.println("Connection request accepted..."); } do { status = clientLink.readMessage(); if (status == ReadMessageStatus.ReadDataCompleted) { try { String keyRoom = (String) clientLink.getData(); theChat = theWorkers.get(keyRoom); if(theChat == null) { createChatRoom(keyRoom); } int roomPort = -1; if (theChat.getStatus() != ConnexionState.allClients) { roomPort = theChat.getNumber(); if (debug) { System.out.println("Sending room num " + theChat.getNumber() +" to Client for key " + keyRoom); } } clientLink.sendMsg(2, roomPort); } catch(ClassCastException cCe) { cCe.printStackTrace(); } break; } else { if (status == ReadMessageStatus.ChannelClosed){ System.out.println("Channel early closed"); } } } while(status != ReadMessageStatus.ChannelClosed); clientLink.close(); } } catch (ClosedChannelException e) { e.printStackTrace(); return; } catch (IOException e) { e.printStackTrace(); return; } } private static void createChatRoom(String keyRoom) throws IOException { if (debug) { System.out.println("Creating chatroom for key " + keyRoom); } theChat = new ChatRoomServer(workerPort,2); theWorkers.put(keyRoom, theChat); workerPort++; } }