thufir

Connection

Sep 16th, 2013
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.34 KB | None | 0 0
  1. package telnet;
  2.  
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.InetAddress;
  6. import java.net.SocketException;
  7. import java.util.Deque;
  8. import java.util.Observable;
  9. import java.util.Observer;
  10. import java.util.logging.Logger;
  11. import org.apache.commons.net.telnet.TelnetClient;
  12. import player.GameAction;
  13. import player.Player;
  14. import player.Regex;
  15.  
  16. public class TelnetConnection implements Observer {
  17.  
  18.     private static Logger log = Logger.getLogger(TelnetConnection.class.getName());
  19.     private TelnetClient telnetClient = new TelnetClient();
  20.     private InputOutput inputOutput = new InputOutput();
  21.     private Regex rx = new Regex();
  22.     private Player player = null;
  23.     private Logic logic = new Logic();
  24.  
  25.     public TelnetConnection() {
  26.         init();
  27.     }
  28.  
  29.     private void init() {
  30.         try {
  31.             int port = 6789;
  32.             InetAddress host = InetAddress.getByName("dune.servint.com");
  33.             telnetClient.connect(host, port);
  34.             inputOutput.readWriteParse(telnetClient.getInputStream(), telnetClient.getOutputStream());
  35.         } catch (SocketException ex) {
  36.         } catch (IOException ex) {
  37.         }
  38.         inputOutput.addObserver(this);
  39.     }
  40.  
  41.     private void sendAction(GameAction action) throws IOException {
  42.         log.info(action.toString());
  43.         byte[] actionBytes = action.getAction().getBytes();
  44.         OutputStream outputStream = telnetClient.getOutputStream();
  45.         outputStream.write(actionBytes);
  46.         outputStream.write(13);
  47.         outputStream.write(10);
  48.         outputStream.flush();
  49.     }
  50.  
  51.     private void sendActions(Deque<GameAction> gameActions) {
  52.         while (!gameActions.isEmpty()) {
  53.             GameAction action = gameActions.remove();
  54.             try {
  55.                 sendAction(action);
  56.             } catch (IOException ex) {
  57.             }
  58.         }
  59.     }
  60.  
  61.     @Override
  62.     public void update(Observable o, Object arg) {
  63.         String line = null;
  64.         if (o instanceof InputOutput) {
  65.             line = inputOutput.getLine();
  66.             log.fine(line);
  67.             player = rx.parse(line);
  68.             Deque<GameAction> gameActions = logic.getActions(player);
  69.             sendActions(gameActions);
  70.         }
  71.     }
  72.  
  73.     public static void main(String[] args) {
  74.         new TelnetConnection();
  75.     }
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment