Ejemplo n.º 1
0
 /**
  * Process a packet received on multicast or unicast ports. Both ports may be used to send connect
  * messages or ordinary messages. Multicast: if from self, ignore. if connect, add or update user,
  * and send a connect reply otherwise display message Unicast: (shouldn't get from self) if
  * connect, add user otherwise display message
  *
  * <p>Notes: we could loopback mode inhibit to true, to stop a socket receiving it's own messages,
  * but that would stop two clients on the same IP address receiving messages from each other
  *
  * @param packet
  * @param multicast
  * @throws IOException
  */
 private void processPacket(DatagramPacket packet, boolean multicast) throws IOException {
   String message = new String(packet.getData(), 0, packet.getLength());
   String type = multicast ? "multicast" : "unicast";
   System.out.println(
       type
           + " packet received from "
           + packet.getAddress().getHostAddress()
           + ":"
           + packet.getPort()
           + "='"
           + message
           + "'");
   // e.g. connect::name=John::host=192.168.2.1::port=8002
   String[] tokens = message.split("::");
   if (tokens.length == 4
       && tokens[0].equals("connect")
       && tokens[1].startsWith("name=")
       && tokens[2].startsWith("host=")
       && tokens[3].startsWith("port=")) {
     String name = tokens[1].substring(5);
     String host = tokens[2].substring(5);
     int port = Integer.parseInt(tokens[3].substring(5));
     User user = new User(name, host, port);
     // check to see if trying to add itself:
     if (user.equals(this.selfUser)) {
       assert (multicast) : "shouldn't receive unicast from self";
       System.out.println("ignoring message from self");
       return;
     }
     chatSwing.addUser(user);
     // if multicast then must be new user or reconnecting user
     // if unicast, then user must already know about me
     if (multicast) {
       // new user, so send back a connect message
       System.out.println("sending back connect message to user " + name);
       String message2 =
           "connect::name=" + userName + "::host=" + myHostAddress + "::port=" + unicastPort;
       SendDatagram.sendDatagram(host, port, message2);
     }
   } else {
     chatSwing.showMessage(message);
   }
 }
Ejemplo n.º 2
0
 public void sendMessage(User user, String message) throws IOException {
   message = "from " + userName + " to " + user.getName() + ": " + message;
   SendDatagram.sendDatagram(user.getHost(), user.getPort(), message);
 }