// Called when a peer we're trying to connect to sends us a message private void processNewPeer(SocketChannel c) throws IOException { ByteBuffer message = ChannelHelper.readBytes(c, 4); String recognize = utf8.decode(message).toString(); if (!recognize.equals("bam!")) { // Connected to something that wasn't a BAMPong client... c.close(); Peer p = new_peers.remove(c); log("Closing attempt to " + p.getName() + " got " + recognize); return; } // Assemble response ByteBuffer name = utf8.encode(nick); message = ByteBuffer.allocateDirect(name.limit() + 10); // id(4), port(4), name(2+limit) message.putInt(id); message.putInt(getPort()); ChannelHelper.putString(message, name); message.flip(); // Send message c.write(message); // Move socket to connected peers. Peer peer = new_peers.remove(c); peers.put(c, peer); sockets.put(peer, c); }
/** Send a debug message to all connected peers. */ public void sendDebug(String message) throws IOException { ByteBuffer msg = utf8.encode(message); ByteBuffer buff = ByteBuffer.allocateDirect(msg.limit() + 3); buff.put(MSG_DEBUG); ChannelHelper.putString(buff, msg); buff.flip(); for (SocketChannel c : peers.keySet()) { ChannelHelper.sendAll(c, buff); buff.rewind(); } }