public static boolean checkMessage(String s1, String s2, SocketChannel sc) { if (s1 == null || s1 == null) { sendMessage(sc, MessageUtils.message("<server>", "bad message")); System.out.println("Bad message from " + getNickFromSocket(sc)); return false; } return true; }
public static void disconnectClient(SocketChannel sc) { String clientName = getNickFromSocket(sc); if (clientName == null) { Utils.printErrorAndExit("Error: it could not happen"); } sendMessage(sc, MessageUtils.bye()); clients.remove(clientName); Utils.tryClose(sc); notifyAllClients(clientName + " leave this chatroom"); System.out.println(clientName + " leave this chatroom"); }
static void disconnect(boolean mustSendByeMessage) { try { if (mustSendByeMessage) { send(curSocketChannel, MessageUtils.bye()); } if (curSocketChannel != null) { curSocketChannel.close(); servers.remove(curHost); isConnected = false; } } catch (Exception ex) { System.err.println(ex.getMessage()); System.exit(1); } System.out.println("You have successfully disconnected from the server"); }
static void exit() { try { Iterator it = servers.entrySet().iterator(); Map.Entry me; while (it.hasNext()) { me = (Map.Entry) it.next(); SocketChannel scToClose = (SocketChannel) me.getValue(); if (scToClose != null) { send(scToClose, MessageUtils.bye()); scToClose.close(); } } } catch (Exception ex) { System.err.println(ex.getMessage()); System.exit(1); } servers.clear(); System.out.println("Exit successfully."); System.exit(0); }
protected void onEditTextChanged(Editable s) { Dialog dlg = getDialog(); if (dlg instanceof AlertDialog) { AlertDialog alertDlg = (AlertDialog) dlg; Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE); if (s.length() == 0) { btn.setEnabled(false); } else { btn.setEnabled(true); } } if (s.length() > mMaxSize) { String title = SimListActivity.this.getResources().getString(R.string.exceed_text_length_limitation); String message = SimListActivity.this .getResources() .getString(R.string.exceed_text_length_limitation_info); MessageUtils.showErrorDialog(SimListActivity.this, title, message); getEditText().setText(""); } }
public static void kill(StringTokenizer st) { try { if (st.hasMoreTokens()) { String clientName = st.nextToken(); if (clients.containsKey(clientName)) { SocketChannel clientChannel = clients.get(clientName); clients.remove(clientName); sendMessage(clientChannel, MessageUtils.bye()); notifyAllClients(clientName + " leave this chatroom"); System.out.println(clientName + " leave this chatroom"); Utils.tryClose(clientChannel); } else { System.err.println("kill: no such client"); } } else { System.err.println("kill: no client name"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public static void stop() { try { if (port[0] != -1) { for (Entry<String, SocketChannel> client : clients.entrySet()) { if (client.getValue().isConnected()) { sendMessage(client.getValue(), MessageUtils.bye()); Utils.tryClose(client.getValue()); } } Utils.tryClose(serverSocket); clients.clear(); port[0] = -1; } else { System.err.println("stop: already stopped"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public void run() { Selector selector = null; try { curSocketChannel = SocketChannel.open(); InetSocketAddress isa = new InetSocketAddress(curHost, curPort); curSocketChannel.connect(isa); curSocketChannel.configureBlocking(false); selector = Selector.open(); curSocketChannel.register(selector, SelectionKey.OP_READ); servers.put(curHost, curSocketChannel); send(curSocketChannel, MessageUtils.hello(clientName)); } catch (Exception ex) { System.err.println("Error in getting connection: " + ex.getMessage()); System.exit(1); } try { while (true) { int num = selector.select(); if (num == 0) { continue; } Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { SocketChannel sc = null; try { sc = (SocketChannel) key.channel(); if (sc.equals(curSocketChannel)) { boolean ok = processInput(sc); if (!ok) { key.cancel(); Socket s = null; try { s = sc.socket(); s.close(); } catch (IOException ie) { System.err.println("Error closing socket " + s + ": " + ie); System.exit(1); } } } } catch (IOException ie) { key.cancel(); String serverToQuitFrom = getKey(sc); if (serverToQuitFrom != null) { IOUtils.closeFile(serverToQuitFrom, sc); servers.remove(serverToQuitFrom); System.out.println(serverToQuitFrom + " was closed."); } } } } keys.clear(); } } catch (Exception ex) { System.err.println(ex.getMessage()); System.exit(1); } }
public static void main(String args[]) throws Exception { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); StringTokenizer tokenizer; String curCommand; String str = ""; String nickname = ""; if (args.length == 0) { System.err.println("Usage: nickname\n"); System.exit(1); } else { nickname = args[0]; } while (true) { curCommand = ""; try { str = br.readLine(); } catch (Exception ex) { System.err.println("Input canceled: " + ex.getMessage()); System.exit(1); } tokenizer = new StringTokenizer(str, " \t"); if (tokenizer.hasMoreTokens()) { curCommand = tokenizer.nextToken(); } if (curCommand.equals("/connect")) { if (tokenizer.countTokens() != 1) { System.err.println("Connect usage: /connect host:portNumber"); } else { String hostPort = tokenizer.nextToken(); int hostPortSeparator = hostPort.indexOf(':'); if (hostPortSeparator == -1) { System.err.println("Connect usage: /connect host:portNumber"); continue; } String host = hostPort.substring(0, hostPort.indexOf(':')); int port; try { port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1)); } catch (Exception ex) { System.err.println("Invalid hostPort: " + hostPort); continue; } System.out.println(host + ":" + port); if (servers.containsKey(host)) { System.out.println("You are already connected to this host"); } else { new Client(host, port, nickname); } } } else if (curCommand.equals("/disconnect")) { if (tokenizer.countTokens() != 0) { System.err.println("Disconnect usage: /disconnect"); } else { disconnect(true); } } else if (curCommand.equals("/whereami")) { if (Client.isConnected) { System.out.println("You are using this host: " + Client.curHost); } else { System.out.println("You haven't connected yet."); } } else if (curCommand.equals("/list")) { if (tokenizer.countTokens() != 0) { System.err.println("List usage: /list"); } else { list(); } } else if (curCommand.equals("/use")) { if (tokenizer.countTokens() != 1) { System.err.println("Use usage: /use host"); } else { use(tokenizer.nextToken()); } } else if (curCommand.equals("/exit")) { if (tokenizer.countTokens() != 0) { System.err.println("Exit usage: /exit"); } else { exit(); } } else { if (Client.isConnected) { send(curSocketChannel, MessageUtils.message(nickname, str)); } else { System.err.println("You haven't got connection yet."); } } } }
public static void checkClients(List<SocketChannel> anonymousClients) { try { if (selector.selectNow() == 0) { return; } Set<SelectionKey> keys = selector.selectedKeys(); for (SelectionKey key : keys) { if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { SocketChannel clientSocket = serverSocket.accept(); if (clientSocket == null) { System.err.println("Error: can not accept"); continue; } anonymousClients.add(clientSocket); clientSocket.configureBlocking(false); clientSocket.register(selector, SelectionKey.OP_READ); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { SocketChannel clientSocket = (SocketChannel) key.channel(); ByteBuffer bytes = ByteBuffer.allocate(4096); if (clientSocket.read(bytes) != -1) { byte[] message = bytes.array(); switch (message[0]) { case 1: { String nick = MessageUtils.parseMessage(message).first; if (!checkMessage(nick, "", clientSocket)) { continue; } if (clients.containsKey(nick) || nick.length() > 32) { if (nick.length() > 32) { sendMessage( clientSocket, MessageUtils.error("<server>: your nick is too long")); } else { sendMessage( clientSocket, MessageUtils.error("<server>: another user is using this nick")); } sendMessage(clientSocket, MessageUtils.bye()); anonymousClients.remove(clientSocket); Utils.tryClose(clientSocket); } else { System.out.println(nick + " enter this chatroom"); notifyAllClients(nick + " enter this chatroom"); sendMessage( clientSocket, MessageUtils.message("<server>", "Wellcome, your nick is " + nick)); anonymousClients.remove(clientSocket); clients.put(nick, clientSocket); } break; } case 2: { String nick = getNickFromSocket(clientSocket); if (nick == null) { Utils.printErrorAndExit("Error: it could not happen"); } Utils.Pair<String, String> pair = MessageUtils.parseMessage(message); if (!checkMessage(pair.first, pair.second, clientSocket)) { continue; } if (!pair.first.equals(nick)) { System.out.println("Cheater: " + nick); sendMessage(clientSocket, MessageUtils.message("<server>", "do not cheat")); } for (Entry<String, SocketChannel> client : clients.entrySet()) { if (!clientSocket.equals(client.getValue())) { sendMessage(client.getValue(), MessageUtils.message(nick, pair.second)); } } break; } case 3: disconnectClient(clientSocket); break; case 127: { String nick = getNickFromSocket(clientSocket); Utils.Pair<String, String> pair = MessageUtils.parseMessage(message); if (!checkMessage(pair.first, pair.second, clientSocket)) { continue; } if (!pair.first.equals(nick)) { System.out.println("Cheater: " + nick); sendMessage(clientSocket, MessageUtils.message("<server>", "do not cheat")); } System.out.println(nick + ": " + pair.second); break; } default: System.out.println("Bad message from " + getNickFromSocket(clientSocket)); sendMessage(clientSocket, MessageUtils.message("<server>", "bad message")); break; } } else { disconnectClient(clientSocket); } } } keys.clear(); } catch (Exception expt) { expt.printStackTrace(); Utils.printErrorAndExit(expt.getMessage()); } }
public static void readCommand() { try { if (!reader.ready()) { return; } StringTokenizer tokens = new StringTokenizer(reader.readLine()); if (tokens.hasMoreTokens()) { switch (tokens.nextToken()) { case "/listen": listen(tokens); break; case "/stop": stop(); break; case "/list": if (port[0] == -1) { System.err.println("Error: start listening before"); } for (Entry<String, SocketChannel> client : clients.entrySet()) { System.out.println(client.getKey()); } if (clients.entrySet().isEmpty()) { System.out.println("list: no clients online"); } break; case "/send": if (tokens.hasMoreTokens()) { String name = tokens.nextToken(); if (clients.containsKey(name)) { if (tokens.hasMoreTokens()) { sendMessage( clients.get(name), MessageUtils.message("<server>", getMessageFromTokens(tokens))); } else { System.err.println("send: message is empty"); } } else { System.err.println("send: no such client"); } } else { System.err.println("send: no client name"); } break; case "/sendall": if (tokens.hasMoreTokens()) { notifyAllClients(getMessageFromTokens(tokens)); } else { System.err.println("sendall: message is empty"); } break; case "/kill": kill(tokens); break; case "/exit": if (port[0] != -1) { stop(); } Utils.tryClose(selector); System.exit(0); break; default: System.err.print("Error: unknown command"); break; } } else { System.err.println("Error: empty input"); } } catch (Exception expt) { Utils.printErrorAndExit(expt.getMessage()); } }
public static void notifyAllClients(String message) { for (Entry<String, SocketChannel> client : clients.entrySet()) { sendMessage(client.getValue(), MessageUtils.message("<server>", message)); } }