Exemple #1
0
  public void connectToRoom() {
    int chatroom = roomList.getSelectedIndex();
    String roomName = roomList.getSelectedValue();
    try {
      Server.sendLine(outServer, "j");
      Server.sendLine(outServer, chatroom + "");

      String ans = Server.readLine(inServer, "Server/roomconnection");
      roomPort = Integer.parseInt(ans); // error if not the port but "f" for failed, noob

      roomSocket = new Socket(serverC, roomPort);
      inRoom = new BufferedReader(new InputStreamReader(roomSocket.getInputStream()));
      outRoom = new PrintWriter(roomSocket.getOutputStream());

      Server.sendLine(outRoom, tfUsername.getText());

      connectedToRoom = true;
      btnConnect.setText("Leave room");
      lRoomname.setText("Room: " + roomName);
    } catch (Exception e) {
      msgChat(e.getMessage());
      try { // same as the standard disconnect from server
        inServer.close();
        outServer.close();
        serverSocket.close();
        connectedToServer = false;
        btnConnectServer.setText("Connect to server");
        enableButtons(false);
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
Exemple #2
0
 @Override
 public void run() {
   running = true;
   while (running) {
     try {
       if (connectedToRoom) {
         Server.sendLine(outRoom, "");
         String msg = Server.readLine(inRoom, "Chatroom");
         if (!msg.isEmpty()) {
           msgChat(msg);
         }
       }
     } catch (Exception e) {
       msgChat(e.getMessage());
       try { // same as the standard disconnect from room
         inRoom.close();
         outRoom.close();
         roomSocket.close();
         connectedToRoom = false;
         btnConnect.setText("Connect to room");
         lRoomname.setText("Room: ---");
       } catch (IOException e1) {
         e1.printStackTrace();
       }
     }
   }
 }
  @Override
  public void ParseIn(Connection Main, Server Environment) {
    Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom);

    if (Room == null) {
      return;
    }

    Main.Data.BadgesSelected.clear();

    for (int i = 0; i < SLOTS; i++) {
      int Slot = Main.DecodeInt();

      Badge badge = Main.GetBadge(Main.DecodeString());
      if (badge != null) {
        badge.Slot = Slot;
        Main.Data.BadgesSelected.add(badge);
      }
    }

    ServerMessage Message = new ServerMessage();
    Environment.InitPacket(228, Message);
    Environment.Append(Main.Data.Id, Message);
    Environment.Append(Main.Data.BadgesSelected.size(), Message);
    for (Badge Badge : Main.Data.BadgesSelected) {
      Environment.Append(Badge.Slot, Message);
      Environment.Append(Badge.Code, Message);
    }
    Room.SendMessage(Message);
  }
 public void startServer(String rootDirectory, int port, WebServer webServer) {
   ServerSocket server = null;
   server1 = new Server(webServer, rootDirectory);
   server2 = new Server(webServer, rootDirectory);
   try {
     server = new ServerSocket(port);
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   while (true) {
     try {
       connection = server.accept();
     } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
     if (this.currentServer == 1) {
       server1.addSocket(connection);
       new Thread(server1).start();
       currentServer = 2;
     } else {
       server2.addSocket(connection);
       new Thread(server2).start();
       currentServer = 1;
     }
   }
 }
 public static void main(String[] args) throws NumberFormatException, IOException {
   if (args.length != 1) {
     System.out.println(USAGE);
     System.exit(0);
   }
   Server server = new Server(Integer.parseInt(args[0]));
   server.run();
 }
Exemple #6
0
 public static void console() {
   String st = b.getText();
   b.setText(null);
   arr = st.split("\\ ");
   if (arr[0].contains("he")) {
     help();
   } else if (arr[0].equalsIgnoreCase("system")) {
     if (arr[1].equalsIgnoreCase("shutdown")) {
       if (arr.length == 2) System.exit(1);
       else if (arr[2].equalsIgnoreCase("cancel")) {
         run.ok = false;
         debug("Shutdown cancelled");
       } else {
         t = new Thread(new run(Integer.parseInt(arr[2])));
         t.start();
         debug("shutdown started. Server will stop in " + arr[2] + "  seconds");
       }
     } else if (arr[1].contains("top")) {
       if (arr[2].equalsIgnoreCase("TRUE")
           || arr[2].equalsIgnoreCase("ON")
           || arr[2].equalsIgnoreCase("1")) {
         f.setAlwaysOnTop(true);
         debug("Frame always on top");
       } else if (arr[2].equalsIgnoreCase("FALSE")
           || arr[2].equalsIgnoreCase("OFF")
           || arr[2].equalsIgnoreCase("0")) {
         f.setAlwaysOnTop(false);
         debug("Frame no longer always on top");
       } else help();
     } else if (arr[0].equalsIgnoreCase("kick")) {
       Iterator i = s.clients.iterator();
       while (i.hasNext()) {
         Socket s = (Socket) i.next();
         if (arr[1].equalsIgnoreCase(s.getInetAddress().toString())) {
           try {
             s.getInputStream().close();
             s.getOutputStream().close();
             s.close();
           } catch (IOException e) {
           }
         }
       }
     } else help();
   } else if (arr[0].equalsIgnoreCase("broad")
       || arr[0].equalsIgnoreCase("bcast")
       || arr[0].equalsIgnoreCase("broadcast")) s.broadcastMessage(arr[1]);
   else if (arr[0].equalsIgnoreCase("list")) {
     if (arr[1].equalsIgnoreCase("client")) {
       s.ListClients();
     }
   } else help();
 }
  @Override
  public void ParseIn(Connection Main, Server Environment) {
    int RoomId = Main.DecodeInt();

    Collection<Integer> l = new ArrayList<Integer>();
    l.add(RoomId);
    Main.Data.Favorite_Rooms.removeAll(l);

    Environment.InitPacket(459, Main.ClientMessage);
    Environment.Append(RoomId, Main.ClientMessage);
    Environment.Append(false, Main.ClientMessage);
    Environment.EndPacket(Main.Socket, Main.ClientMessage);
  }
  public static void ItemonObject(Client c, int objectID, int objectX, int objectY, int itemId) {
    if (!c.getItems().playerHasItem(itemId, 1)) return;
    switch (objectID) {
      case 15621:
        Server.getWarriorsGuild().handleArmor(c, itemId, objectX, objectY);
        break;
      case 2783:
        c.getSmithingInt().showSmithInterface(itemId);
        break;
      case 8151:
      case 8389:
        c.getFarming().checkItemOnObject(itemId);
        break;
      case 2644:
        c.getFlaxStringer().itemOnObject(itemId);
        break;

      case 409:
        if (c.getPrayer().IsABone(itemId)) c.getPrayer().bonesOnAltar(itemId);
        break;
      default:
        if (c.playerRights == 3)
          Misc.println("Player At Object id: " + objectID + " with Item id: " + itemId);
        break;
    }
  }
Exemple #9
0
 /**
  * Startet einen neuen SlimeSoccer Client Wird die Option -s beim start angegeben, wird anstantt
  * des Clients ein Server gestartet Beim Server kann als weitere Option ein Port folgen
  *
  * @param args -s für Server, ansonsten wird ein Client gestartet
  */
 public static void main(String[] args) {
   if (args.length >= 1 && "-s".equals(args[0])) {
     server.Server.main(Arrays.copyOfRange(args, 1, args.length));
   } else {
     client.Client.main("");
   }
 }
 /**
  * Diese Methode erhält das Paket. Darauf hin wird eine Lognachricht erzeugt. Im Anschluss wird
  * der Listener für den Datenkanal aus dem Server entfernt und die GUI mitr den Daten des Geräts
  * upgedatet.
  *
  * @param p Das Paket
  * @param temp_imei Eine IMEI
  * @param c Der Server
  */
 @Override
 public void handlePacket(Packet p, String temp_imei, Server c) {
   gui.logTxt("Call monitoring data has been received");
   c.getChannelHandlerMap().get(imei).getStorage(channel).reset();
   CallStatusPacket packet = (CallStatusPacket) p;
   gui.addMonitoredCall(imei, packet.getType(), packet.getPhonenumber());
 }
 @Override
 public void handlePacket(Packet p, String temp_imei, Server c) {
   gui.logTxt("SMS data has been received");
   c.getChannelHandlerMap().get(imei).getStorage(channel).reset();
   ShortSMSPacket packet = (ShortSMSPacket) p;
   gui.addMonitoredSMS(imei, packet.getAddress(), packet.getDate(), packet.getBody());
 }
 protected Item findItem(String itemName) {
   for (Item item : Server.getInstance().getItemList()) {
     if (item.getName().equals(itemName)) {
       return item;
     }
   }
   return null;
 }
Exemple #13
0
 public void getList() throws Exception {
   try {
     Server.sendLine(outServer, "g");
     String name;
     List<String> roomNames = new ArrayList<String>();
     do {
       name = Server.readLine(inServer, "Server/request roomlist");
       if (name.equals("e")) {
         break;
       }
       roomNames.add(name);
     } while (true);
     roomList.setListData(roomNames.toArray(new String[1]));
     roomList.setSelectedIndex(0);
   } catch (Exception e) {
     throw e;
   }
 }
 public void stillGraphics(Client curPlr, int absX, int absY, int heightLevel, int id, int pause) {
   for (Player p : Server.getPlayerManager().getClientRegion((curPlr).currentRegion)) {
     if (p == null) continue;
     if (!p.isActive) continue;
     if (p.disconnected) continue;
     Client c = (Client) p;
     if (c == curPlr || c.withinDistance(absX, absY, heightLevel)) {
       c.getPA().sendStillGraphics(id, heightLevel, absY, absX, pause);
     }
   }
 }
 public void actionPerformed(ActionEvent e) {
   String stringPort = portNumber.getText();
   port = Integer.parseInt(stringPort);
   FileSystem c = new FileSystem();
   try {
     setVisible(false);
     Server.runServer(port, c);
   } catch (IOException e2) {
     e2.printStackTrace();
   }
 }
  public void execute() {
    int result = ServerApplication.bindServerToRoom(serverInvoker, nextRoom);
    if (result == -1) {
      try {
        serverInvoker.sendMessage("There is no such room!");
      } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
      }
      return;
    }
    String login = serverInvoker.getLogin();
    ServerApplication.sendMessageToRoom(prevRoom, String.format("User %s has left us", login));
    ServerApplication.sendMessageToRoom(nextRoom, String.format("User %s has joined us", login));
    log();

    try {
      serverInvoker.sendMessage("you have entered in room #" + nextRoom);
    } catch (IOException e) {
      logger.log(Level.WARNING, e.getMessage(), e);
    }
  }
Exemple #17
0
  @Test
  public void testCanDeclineInvitation() throws Exception {

    Mockito.when(idGenerator.generate()).thenReturn("id1").thenReturn("id2");

    String input = "";

    Socket client1 = new Socket("localhost", 9898);
    Socket client2 = new Socket("localhost", 9898);

    ObjectOutputStream o1 = new ObjectOutputStream(client1.getOutputStream());
    ObjectInputStream i1 = new ObjectInputStream(client1.getInputStream());

    // Client 1 connection
    o1.writeObject("000|Hans");
    input = (String) i1.readObject();
    String id1 = input.split("\\|")[1].split(",")[0];

    ObjectOutputStream o2 = new ObjectOutputStream(client2.getOutputStream());
    ObjectInputStream i2 = new ObjectInputStream(client2.getInputStream());

    o2.writeObject("000|John");

    // Connection established
    input = (String) i2.readObject();

    // Read player list - One for own connection and one for other connection
    i1.readObject();
    i1.readObject();

    // Find player 2 id
    String id2 = input.split("\\|")[1].split(",")[0];

    // Player list
    input = (String) i2.readObject();

    // Send invite
    o1.writeObject("005|" + id2 + "," + "tictactoe" + "," + id1);

    input = (String) i2.readObject();
    String[] splitted = input.split("\\|");
    String invitationReceiverId = splitted[1].split(",")[0];
    String invitationSenderId = splitted[1].split(",")[2];
    String gameType = splitted[1].split(",")[1];

    o2.writeObject("010|" + invitationSenderId);

    input = (String) i1.readObject();

    assertEquals("010|id1", input);

    server.stop();
  }
Exemple #18
0
  public void disconnectFromRoom() {
    try {
      Server.sendLine(outRoom, "e");

      inRoom.close();
      outRoom.close();
      roomSocket.close();
      connectedToRoom = false;
      btnConnect.setText("Connect to room");
      lRoomname.setText("Room: ---");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private void log() {
   String login = serverInvoker.getLogin();
   if (login != null) {
     if (prevRoom > 0 & nextRoom > 0) {
       logger.info(
           String.format(
               "User %s has moved from room #%d to room #%d", login, prevRoom, nextRoom));
     } else if (prevRoom == 0 & nextRoom > 0) {
       logger.info(
           String.format("User %s has moved from general chat to room #%d", login, nextRoom));
     } else if (prevRoom > 0 & nextRoom == 0) {
       logger.info(
           String.format("User %s has moved from room #%d to general chat", login, prevRoom));
     }
   }
 }
Exemple #20
0
 public void run() {
   try {
     b = new byte[6300];
     line.open(new AudioFormat(44100, 16, 1, true, true), 6300);
     line.start();
     while (true) {
       line.read(b, 0, b.length);
       server.writeByteBuffers(b, sourceIndex);
       if (output) serverOutput.write(b, 0, b.length);
     }
   } catch (LineUnavailableException e) {
     e.printStackTrace();
     System.out.println(sourceIndex);
   } finally {
     line.stop();
     line.close();
   }
 }
Exemple #21
0
  public void disconnectFromServer() {
    try {
      if (connectedToRoom) {
        disconnectFromRoom();
      }

      Server.sendLine(outServer, "e");

      inServer.close();
      outServer.close();
      serverSocket.close();
      connectedToServer = false;
      btnConnectServer.setText("Connect to server");
      enableButtons(false);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #22
0
  @Test
  public void testCanConnectOneClient() throws Exception {

    Mockito.when(idGenerator.generate()).thenReturn("a0b257f5-5b0b-40bc-9793-aa324b7e3ab2");

    Socket socket = new Socket("localhost", 9898);

    ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

    outputStream.writeObject("000|Hans");
    String input = (String) inputStream.readObject();

    outputStream.close();
    inputStream.close();
    server.stop();

    Assert.assertEquals(input, "008|a0b257f5-5b0b-40bc-9793-aa324b7e3ab2,Hans");
  }
Exemple #23
0
  @Test
  public void testCanInvitePersonToGame() throws Exception {

    Mockito.when(idGenerator.generate()).thenReturn("id1").thenReturn("id2");

    String input = "";

    Socket client1 = new Socket("localhost", 9898);
    Socket client2 = new Socket("localhost", 9898);

    ObjectOutputStream oSClient1 = new ObjectOutputStream(client1.getOutputStream());
    ObjectInputStream iSClient1 = new ObjectInputStream(client1.getInputStream());

    ObjectOutputStream oSClient2 = new ObjectOutputStream(client2.getOutputStream());

    oSClient1.writeObject("000|Hans");
    // Connection established
    input = (String) iSClient1.readObject();
    String id1 = input.split("\\|")[1].split(",")[0];

    oSClient2.writeObject("000|John");

    ObjectInputStream iSClient2 = new ObjectInputStream(client2.getInputStream());
    // Connection established
    input = (String) iSClient2.readObject();

    // Find player 2 id
    String id2 = input.split("\\|")[1].split(",")[0];

    // Player list
    input = (String) iSClient2.readObject();

    // Send invite
    oSClient1.writeObject("005|" + id2 + "," + "tictactoe" + "," + id1);

    input = (String) iSClient2.readObject();

    assertEquals("005|id2,tictactoe,id1", input);

    server.stop();
  }
Exemple #24
0
  @Test
  public void testCanConnectMultipleClients() throws Exception {

    when(idGenerator.generate()).thenReturn("a0b257f5-5b0b-40bc-9793-aa324b7e3ab2");

    TestRunnable client1 = makeClient("Hans");
    TestRunnable client2 = makeClient("John");
    TestRunnable client3 = makeClient("Joe");

    new Thread(client1).start();
    new Thread(client2).start();
    new Thread(client3).start();

    Thread.sleep(200);

    Assert.assertEquals("008|a0b257f5-5b0b-40bc-9793-aa324b7e3ab2,Hans", client1.getOutput());
    Assert.assertEquals("008|a0b257f5-5b0b-40bc-9793-aa324b7e3ab2,John", client2.getOutput());
    Assert.assertEquals("008|a0b257f5-5b0b-40bc-9793-aa324b7e3ab2,Joe", client3.getOutput());

    server.stop();
  }
 public void run() {
   try {
     this.tcpCommunication = new TCPCommunication(clientSocket);
   } catch (IOException e) {
     exit();
     return;
   }
   while (!interrupted() && clientSocket != null) {
     try {
       String receivedMessage = tcpCommunication.receive();
       if (receivedMessage == null) {
         exit();
         break;
       }
       server.receiveMessage(receivedMessage, clientSocket);
     } catch (IOException e) {
       exit();
     }
   }
   // TODO perhaps send disconnect event from here
 }
 @Override
 public void placeItemForBid(
     String ownerName,
     String itemName,
     String itemDesc,
     double startBid,
     int auctionTime,
     String auctionType)
     throws RemoteException {
   List<Item> items = Server.getInstance().getItemList();
   BiddingStrategyValidator validator;
   if (auctionType.equals("English")) {
     validator = new EnglishAuctionBiddingStrategyValidator();
   } else {
     validator = new DutchAuctionBiddingStrategyValidator();
   }
   Item newItem =
       new Item(
           ownerName,
           itemName,
           itemDesc,
           startBid,
           null,
           auctionTime,
           validator,
           Calendar.getInstance());
   if (items.contains(newItem)) {
     throw new RemoteException("Item with that name already exists!");
   } else {
     items.add(newItem);
     System.out.println(
         "Wystawiono przedmiot "
             + newItem
             + " na aukcje typu "
             + newItem.getValidator().getClass().getName()
             + ".");
   }
 }
  @Override
  public void run() {
    int count = max_count;

    if (console != null) {
      window.setLockElements(false);
    }

    writeIn(
        "\n> Préparation à l'extinction du serveur. Veuillez patienter...\n> Sauvegarde dans la base de données...");
    server.getDbInfos().saveDatabase();
    writeIn("Terminé !\n> Annonce aux joueurs de l'interruption serveur...");
    writeIn("Terminé !\n> Arrêt du serveur dans 10 secondes...");

    while (count > 0) {
      try {
        sleep(TIMER_PERIOD);
      } catch (InterruptedException e) {
      }
      count--;
    }
    System.exit(0);
  }
  @Override
  public void ParseIn(Connection Main, Server Environment) {
    Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom);

    if (Room == null) {
      return;
    }

    int index = Main.DecodeInt();
    TraxSong Song2 = Room.TraxPlaylist.PlaylistByIndex.get(index);
    Main.AddItem(Song2.ItemId, Integer.toString(Song2.SongId), Song2.BaseItem, true);
    Room.TraxPlaylist.PlaylistByIndex.remove(index);

    Environment.InitPacket(333, Main.ClientMessage);
    Environment.Append(Main.Data.SongInInventory.size(), Main.ClientMessage);
    for (int Key : Main.Data.SongInInventory.keySet()) {
      int Value = Main.Data.SongInInventory.get(Key);
      Environment.Append(Key, Main.ClientMessage);
      Environment.Append(Value, Main.ClientMessage);
    }
    Environment.EndPacket(Main.Socket, Main.ClientMessage);

    Environment.InitPacket(334, Main.ClientMessage);
    Environment.Append(0, Main.ClientMessage);
    Environment.Append(Room.TraxPlaylist.PlaylistByIndex.size(), Main.ClientMessage);
    int count = 0;
    for (TraxSong Song : Room.TraxPlaylist.PlaylistByIndex) {
      Environment.Append(count++, Main.ClientMessage);
      Environment.Append(Song.SongId, Main.ClientMessage);
    }
    Environment.EndPacket(Main.Socket, Main.ClientMessage);
  }
 public void closeAuction(String itemName) throws RemoteException {
   Item item = findItem(itemName);
   notifyObservers(item, "close");
   Server.getInstance().getItemList().remove(item);
   listeners.remove(itemName);
 }
 @Override
 public Item[] getItems() throws RemoteException {
   return (Item[]) Server.getInstance().getItemList().toArray();
 }