Client.java

jmud-0.11/src/Client.java · 10.9 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.net.Socket;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;

import util.file.InvalidFileFormatException;
import util.list.Queue;
import misc.Separators;
import string.StrUtil;
import util.log.Log;
import util.nice.NiceEnumeration;

class Client extends Thread {

    static private Manager theManager = null;
    static final int MAX_NAME_LENGTH  = 10;
    static final int MAX_INPUT_LENGTH = 256;
    static final int MAX_CMD_SLOTS    = 10;

  static void setManager(Manager aManager) {
    theManager = aManager;
  }
    
    private int            theId        = -1;
    private Socket         clientSocket = null;
    private Char           theChar      = null;
    private BufferedReader is           = null;
    private BufferedWriter os           = null;
    private String         hostName     = null;
    private String         clientName   = null;
    private Config         theConfig    = null;
    private boolean        playing;
    private Counter        cmdSlots     = new Counter();
    private Counter        delaySlots   = new Counter();
    private Queue          commands     = new Queue();
    private String         lastCommand  = ""; // DEVE ser string vazia
    private int            maxSpam;
    private int            spam         = 0;
    private String         msgBuffer    = "";
    private boolean        prompt       = false;
    
    private TextBuffer     text         = new TextBuffer();

  Client(Config aConfig, Socket aSocket) 
    throws IOException {
    theConfig  = aConfig;
    clientSocket = aSocket;
    is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    os = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
    hostName = clientSocket.getInetAddress().getHostName();
    maxSpam = theConfig.getMaxSpam();
  }

    ////////////
    // Annotate:

    void lookNote() {
	String note = "";
	int i = 1;
	for (Enumeration enum = text.elements(); enum.hasMoreElements(); ++i) {
	    String str = (String) enum.nextElement();
	    note += Separators.NL + StrUtil.formatNumber(i, 2) + ": " + str;
	}

	send("Anotações:" + (note.length() == 0 ? (Separators.NL + "Nenhuma") : note));
    }

    String getNoteText() {
	return text.toString();
    }

    void addNoteLine(String str) {
	text.insertAtEnd(str);
    }

    void remNoteLine() {
	text.removeFromEnd();
    }

    void clearNote() {
	text.clear();
    }

    int getNoteSize() {
	return text.getSize();
    }

    void buildNote(String txt) {
	text.buildFrom(txt);
    }

    //
    ////////////

  Char getChar() {
    return theChar;
  }

  String getUserName() {
    return clientName + " [" + theId + "] (" + hostName + ")";
  }

  String getHostName() {
    return hostName;
  }

  boolean hasName(String name) {
    return clientName.equalsIgnoreCase(name);
  }

  int getId() {
    return theId;
  }

  void rawSend(String msg) {
    try {
      os.write(msg);
      os.flush();
    }
    catch(IOException e) {
      // Log não pode ser usado, pois ele próprio usa "send"
      // (para fazer broadcast do erro aos monitores)
    }
  }

  void flush() {
    if (msgBuffer.length() > 0) {
      rawSend(msgBuffer + Separators.NL + theChar.getPrompt());
      msgBuffer = "";
    }
    else if (prompt) {
      rawSend(theChar.getPrompt());
      prompt = false;
    }
  }

  void send(String msg) {
    msgBuffer += Separators.NL + msg;
  }

  String receive() {
      String line = null;

      try {
	  line = is.readLine();

	  // aqui line nao dever ser null
	  if (line.length() > MAX_INPUT_LENGTH) {
	      Log.warn("Truncando entrada muito longa para: " + getUserName());
	      line = line.substring(0, MAX_INPUT_LENGTH);
	  }
      }
      catch(IOException e) {
	  Log.err("Falha ao receber mensagem de: " + getUserName());
      }

      return line;
  }

  void closeSocket() {
    Log.log("Fechando conexão para: " + getUserName());

    try {
      clientSocket.close();
    }
    catch(IOException e) {
      Log.err("Falha ao fechar socket: " + getUserName());
    }
  }

  void disconnect() {
    closeSocket();
  }

  void reject() {
    theManager.retreat(this);
    disconnect();
  }

  boolean isValidName(String name) {
    if (name == null || name.length() < 1 || name.length() > MAX_NAME_LENGTH)
      return false;

    for (int i = 0; i < name.length(); ++i) {
      char ch = name.charAt(i);
      if ((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'))
	return false;
    }

    return true;
  }

  void saveChar() {
      // Quando o Mud capota e o personagem esta' salvo,
      // mas o estado nao, ocorrem problemas.
      // A linha a seguir garante que o estado
      // sempre esteja consistente com os personagens salvos
      // mesmo em caso de crash.
      theManager.saveState();

      Log.info("Gravando usuário: " + getUserName(), Debug.full);

      try {
	  theChar.save(theId, theConfig);
      }
      catch (IOException e) {
	  Log.err("Falha ao gravar usuário: " + getUserName());
      }

      Log.info("Gravando itens para: " + getUserName(), Debug.full);

      ((Player) theChar).saveItems(theConfig);
  }

    private Player loadPlayer(String name) {
    
	for (NiceEnumeration enum = theManager.getClientMapEnum(); enum.hasMoreElements(); ) {
	    StrIntPair pair = (StrIntPair) enum.nextElement();
	    int id = pair.getInt();
	
	    if (name.equalsIgnoreCase(pair.getStr())) {
		Player pl = null;
		try {
		    pl = new Player(this, String.valueOf(id), theConfig);
		    if (!pl.isDeleted() || id == 0) {
			this.theId = id;
			return pl;
		    }
		}
		catch(IOException e) {
		    Log.err("Falha de E/S ao ler arquivo de usuário: " + id);
		}
		catch(InvalidFileFormatException e) {
		    Log.err("Arquivo de usuário com formato inválido: " + id);
		}
	    }
	}

	return null;
    }
    
    void addDelay(int delay) {
	delaySlots.inc(delay);
    }

  synchronized private void addCmd(String cmd) {
    commands.insert(cmd);
  }

  synchronized private Request getCmd() {
    return commands.isEmpty() ? null : new Request(theChar, (String) commands.remove());
  }

  Request oneRequest() {
      if (delaySlots.decIfGreaterThan(0))  
	  return null;

      Request req = getCmd(); // synchronized: commands
      if (req != null)	 
	  cmdSlots.dec();       

      return req;
  }

  private void treatCommand(String cmd) {

      if (cmdSlots.incIfLessThan(MAX_CMD_SLOTS))
	  addCmd(cmd);          // synchronized: commands
      else if (Debug.cmd)
	  Log.warn("Estouro da fila de comandos: " + theChar.getName() + " {" + cmd + "}");
  }

  void parse(String cmdLine) {  

    if (Debug.cmd)
      Log.log("Client: " + theChar.getName() + " {" + cmdLine + "}");

    boolean repeat = cmdLine.startsWith("!");

    // joga brancos fora
    cmdLine = cmdLine.trim();

    boolean empty = cmdLine.length() == 0;

    // dificulta spamming
    if (empty || repeat || cmdLine.equals(lastCommand)) {
      if (++spam == maxSpam)
	if (Debug.cmd)
	  Log.log("Abuso: " + getUserName());
      if (spam >= maxSpam)
	return;                     // ou alguma maldade calculista
    }
    else
      spam = 0;

    // ignora comando vazio
    if (empty) {
      prompt = true; 
      return;
    }

    // repete último comando
    if (repeat)
      cmdLine = lastCommand;
    else
      lastCommand = cmdLine;
    
    // extrai os comandos de uma linha separados por ';' (ponto-e-vírgula)
    for (StringTokenizer cmds = new StringTokenizer(cmdLine, ";") ; cmds.hasMoreTokens(); ) {
      String cmd = cmds.nextToken().trim();
      if (cmd.length() != 0)
	treatCommand(cmd);
      }
  }

  public void run() {
    Log.log("Nova conexão de: " + hostName);

    rawSend("\r\nDISCLAIMENT NOTICE" +
	    "\r\n" +
	    "\r\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY" +
	    "\r\nFOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES" +
	    "\r\nARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY" +
	    "\r\nDERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE" +
	    "\r\nPOSSIBILITY OF SUCH DAMAGE." +
	    "\r\n" +
	    "\r\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY" +
	    "\r\nWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES" +
	    "\r\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND" +
	    "\r\nNON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN \"AS IS\" BASIS," +
	    "\r\nAND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE" +
	    "\r\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." +
	    "\r\n");

    rawSend(Separators.NL + StrUtil.centerPad("Benvindo ao JMud!", 80) + Separators.NL + Separators.NL +
	    StrUtil.centerPad("Autor: Everton da Silva Marques <evertonm@dcc.unicamp.br>", 80) + Separators.NL + 
	    /* StrUtil.centerPad("Colaboração: Fabrício Matheus Gonçalves <fmatheus@dcc.unicamp.br>", 80) + */ 
	    Separators.NL + Separators.NL +
	    "Nome: ");


    //
    // Obtém nome do personagem
    //
    clientName = receive();
    
    if (!isValidName(clientName)) {
      Log.log("Cliente com nome inválido: " + getUserName());
      rawSend("Nome inválido." + Separators.NL);
      reject();
      return;
    }
    
    clientName = Character.toUpperCase(clientName.charAt(0)) + clientName.substring(1);
    
    //
    // Certifica-se de que o personagem já não está em jogo
    //
    Client dup = null;
    try {
      dup = theManager.findClientByName(clientName);
      Log.log("Desconectando cliente duplicado: " + dup.getUserName());
      dup.saveChar();
      dup.disconnect();
    }
    catch(NoSuchElementException e) {
      // Não está logando com mesmo personagem
    }
    
    //
    // Procura arquivo do personagem
    //
    Player pl = loadPlayer(clientName);
    
    //
    // Conecta o personagem
    //
    if (pl != null) {
      Log.log("Usuário conectado: " + getUserName());
      theChar = pl;
      theManager.play(this, pl.getLoadRoom()); // agenda BeginTask
    }
    else {
      theId = theManager.newClientId();
      theManager.addClientMapEntry(clientName, theId);
      Log.log("Novo usuário: " + getUserName());
      theChar = new Player(this, clientName);
      theManager.play(this);                   // agenda BeginTask
    }

    //
    // Mensagem do dia
    //
    rawSend(theManager.getMotd());

    //
    // Carrega itens do usuário
    //

    Log.info("Carregando itens para: " + getUserName(), Debug.full);
    ((Player) theChar).loadItems(theConfig);

    //
    // Laço de atendimento ao usuário
    //
    for (; ; ) {
      String cmdLine = receive();
      
      if (cmdLine == null) {
	Log.log("Conexão perdida: " + getUserName());
	break;
      }
      
      parse(cmdLine);
      yield();          // dar uma chance aos outros
    }
    
    //
    // Aqui o socket JÁ está desconectado
    //
    
    saveChar();
    
    theManager.quit(this); // agenda QuitTask
  }
}

Site Stats

Snippets: 1791
Codebases: 571