1. Proyecto No. 12- Juego de batallas (Héctor)
2. Proyecto No. 10- Equivalencias. (Luis Eduardo)
3. Proyecto No. 13 -Renta de coches (Andrea)
Y el proyecto de Edgar me pareció interesante la manera en que almacena recupera una imagen .
Este trabajo consistió en programar una aplicación utilizando sockets y RMS(Record Management System).
Se trata de un Diccionario, donde el cliente solicita una palabra (de las ya definidas en el RMS) y el Servidor, proporciona su significado.
A continuación se encuentra el código de dicha aplicación:
______________________________________________________________
package connection;
/*
* Gerardo Ayala
* November 2009
* */
import java.io.*;
class SendMessageTask extends Thread
{
private String message;
OutputStream outputStream;
public synchronized void send( OutputStream theOutputStream,String aMessage )
{
outputStream = theOutputStream;
message = aMessage;
notify();
}//end send
// the run method is synchronized
public synchronized void run()
{
//waits.....for a message to be send
while( true )
{
if( message == null )
{
try
{
wait();
}//end try
catch( Exception e ) {}
}//end if
else
{
try
{
//sends the message
outputStream.write( message.getBytes() );
// and a new line
outputStream.write( "\r\n".getBytes() );
}//end try
catch( IOException e )
{
e.printStackTrace();
}//end catch
message = null;
}//end if
}//end while
}//end run
public synchronized void stop()
{
message = null;
notify();
}//end stop
}//end class SendMessageTask
__________________________________________________________
package connection;
/*
* Gerardo Ayala
* November 2009
* */
import javax.microedition.io.*;
public class SocketConnectionClientMidlet extends SocketConnectionMidlet
{
public String url;
// Constructor
public SocketConnectionClientMidlet()
{
super("Client");
url = "socket://localhost:2500";
}//end constructor
public void run()
{
try{
socketConnection = (SocketConnection)Connector.open( url );
setSocketConnectionOptions();
form.setTitle( "Client -> Connected" );
messageReceived.setText( "Connection established." );
// get and open inpust and output streams
getAndOpenIOStreams();
// creates and starts send message task thread
createsAndStartsSendMessageTask();
// then , to read!!!
readMessagesClient();
}//end try
catch( Exception e )
{
}//end catch
}//end connectToServer
protected void pauseApp() {}
protected void destroyApp( boolean flag ) {}
}//end class SocketConnectionClientMidlet
___________________________________________________________
package connection;
/*
* Gerardo Ayala
* November 2009
* */
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import rms.BusquedaDiccionario;
import rms.PalabraSignificadoRMS;
import rms.Diccionario;
public abstract class SocketConnectionMidlet extends MIDlet
implements CommandListener,
Runnable
{
public Display display;
public Form form;
public TextField messageToSend;
public StringItem messageReceived;
SendMessageTask sendMessageTask;
public Command exitCommand;
public Command sendCommand;
public InputStream inputStream;
public OutputStream outputStream;
public SocketConnection socketConnection;
Thread listeningTask;
private PalabraSignificadoRMS palabraSignificadoRMS = new PalabraSignificadoRMS();
private BusquedaDiccionario busqueda;
public Diccionario seleccion = new Diccionario(
palabraSignificadoRMS.getRecordsByIdByPalabra(),
palabraSignificadoRMS.getRecordsByIdBySignificado());
public SocketConnectionMidlet(String title)
{
form = new Form(title);
messageReceived = new StringItem( null," " );
form.append( messageReceived );
//if(form.getTitle().equals())
messageToSend = new TextField( "Text: ","",1024,TextField.ANY );
form.append( messageToSend );
exitCommand = new Command( "Exit",Command.EXIT,1 );
sendCommand = new Command( "Send",Command.ITEM,1 );
form.addCommand( sendCommand );
form.addCommand( exitCommand );
form.setCommandListener( this );
}//end constructor
public void startApp()
{
display = Display.getDisplay( this );
display.setCurrent( form );
listeningTask = new Thread(this) ;
listeningTask.start();
}//end startApp
protected void pauseApp() {}
protected void destroyApp( boolean flag ) {}
public void readMessages()
{
StringBuffer stringBuffer;
StringBuffer otherStringBuffer;
Resultado();
int characterRead;
while( true )
{
stringBuffer = new StringBuffer();
characterRead = -1;
try
{
while( ((characterRead = inputStream.read()) != -1) &&
(characterRead != '\n') )
{
stringBuffer.append( (char)characterRead );
}//end while
}//end try
catch(Exception e)
{
System.out.println(e);
}//end catch
if( characterRead == -1 )
{
break;
}//end if
else
{
otherStringBuffer = new StringBuffer( messageReceived.getText()+
"\nCliente-> "+stringBuffer.toString() );
messageReceived.setText( otherStringBuffer.toString() );
}//end else
}//end while
}//end readMessages
public void readMessagesClient()
{
StringBuffer stringBuffer;
StringBuffer otherStringBuffer;
int characterRead;
String palabra ="";
busqueda();
while( true )
{
stringBuffer = new StringBuffer();
characterRead = -1;
try
{
while( ((characterRead = inputStream.read()) != -1) &&
(characterRead != '\n') )
{
stringBuffer.append( (char)characterRead );
}//end while
palabra = stringBuffer.toString().trim();
}//end try
catch(Exception e)
{
System.out.println(e);
}//end catch
if( characterRead == -1 )
{
break;
}//end if
else
{
System.out.println("Mensaje recibido del cliente en el servidor:"+messageReceived.getText());
otherStringBuffer = new StringBuffer( messageReceived.getText()+
"\nServidor-> "+stringBuffer.toString() );
messageReceived.setText( otherStringBuffer.toString() );
}//end else
}//end while
}//end readMessagesClient
private void busqueda()
{
busqueda= seleccion.getPosicionPalabra();
sendMessageTask.send(outputStream, "Busqueda: \n" + busqueda.getPalabra());
}
private void Resultado()
{
busqueda= seleccion.getPosicionPalabra();
sendMessageTask.send(outputStream, "Resultado: \n" + busqueda.getSignificado());
}
//the run method for the listening task thread, to override
public abstract void run();
public void setSocketConnectionOptions()
{
try
{
// defines socket connection options
socketConnection.setSocketOption( socketConnection.DELAY,0 );
socketConnection.setSocketOption( socketConnection.KEEPALIVE,0 );
}
catch(Exception e){
}
}//end setSocketConnectionOptions
public void getAndOpenIOStreams()
{
try
{
// get and open output and input streams
inputStream = socketConnection.openInputStream();
outputStream = socketConnection.openOutputStream();
}
catch(Exception e)
{
}
}//end
public void createsAndStartsSendMessageTask()
{
// creates and starts the send message thread
//sendMessageTask = new SendMessageTask();
sendMessageTask = new SendMessageTask();
sendMessageTask.start();
}//end createsAndStartsSendMessageTask
public void commandAction( Command theCommand,Displayable any )
{
if( theCommand == Alert.DISMISS_COMMAND ||
theCommand == exitCommand )
{
try
{
if( inputStream != null )
{
inputStream.close();
}//end if
if( outputStream != null )
{
outputStream.close();
}//end if
if( socketConnection != null )
{
socketConnection.close();
}//end if
}//end try
catch( IOException e ) {}
destroyApp( true );
notifyDestroyed();
}//end if
if (theCommand == sendCommand )
{
sendMessageTask.send( outputStream, messageToSend.getString() );
}//end if
}//end commandAction
}//end class SocketConnectionMidlet
________________________________________________________
package connection;
/*
* Gerardo Ayala
* November 2009
* */
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
public class SocketConnectionServerMidlet extends SocketConnectionMidlet
{
private ServerSocketConnection serverSocketConnection;
private String url;
// Constructor
public SocketConnectionServerMidlet()
{
super("Server");
url = "socket://:2500";
}//end constructor
protected void pauseApp() {}
protected void destroyApp( boolean flag ) {}
public void run()
{
// The ServerSocketConnection interface defines the server socket stream
// connection.
// A server socket is accessed using a generic connection string with
// the host omitted.
// For example, socket://:79 defines an inbound server socket on port 79.
// The host can be discovered using the getLocalAddress method.
// The acceptAndOpen() method returns a SocketConnection instance.
// In addition to the normal StreamConnection behavior, the SocketConnection
// supports accessing the IP end point addresses of the live connection
// and access to socket options that control the buffering and timing delays
// associated with specific application usage of the connection.
// Access to server socket connections may be restricted by the security policy
// of the device.
// Connector.open MUST check access for the initial server socket connection
// and acceptAndOpen MUST check before returning each new SocketConnection.
// A server socket can be used to dynamically select an available port
// by omitting both the host and the port parameters in the connection URL
// string.
// For example, socket:// defines an inbound server socket on a port which
// is allocated by the system.
// To discover the assigned port number use the getLocalPort method.
try
{
messageReceived.setText( "Esperando a cliente..." );
serverSocketConnection = (ServerSocketConnection) Connector.open( url );
// while( true )
// {
form.setTitle( "Server -> en espera..." );
messageReceived.setText( "esperando por conexiones..." );
// Gets a SocketConnection object that represents a server side
// socket connection.
socketConnection = (SocketConnection)
serverSocketConnection.acceptAndOpen();
setSocketConnectionOptions();
form.setTitle( "Server -> Dado de alta" );
messageReceived.setText( "Conexion aceptada " );
getAndOpenIOStreams();
// creates and starts the send message thread
createsAndStartsSendMessageTask();
form.addCommand( sendCommand );
// then, read the messages !!
readMessages();
//}//end while
}//end try
catch( IOException ie )
{
if( ie.getMessage().equals("ServerSocket Open") )
{
Alert a = new Alert( "server","port 2500 already occupied.",
null,AlertType.ERROR );
a.setTimeout( Alert.FOREVER );
a.setCommandListener( this );
display.setCurrent( a );
}//end if
}//end catch
catch( Exception e ) {}
}//end connectionToClient
}//end class controlConexion
___________________________________________________________
package rms;
//@author Paola
public class BusquedaDiccionario
{
private String palabra;
private String Significado;
public BusquedaDiccionario(String palabra, String significado)
{
this.palabra = palabra;
this.Significado = significado;
}//constructor
public String getPalabra()
{
return this.palabra;
}//end getPalabra
_____________________________________________________________
//@author Paola González
package rms;
public class Diccionario
{
private BusquedaDiccionario[] busquedaArray;
private PalabraSignificadoRMS diccionarioRMS;
int posicion=0;
public Diccionario(String[] palabra, String[] significado)
{
busquedaArray = new BusquedaDiccionario[significado.length];
for(int contador=0; contador
{
return true;
}//end if
else
{
return false;
}//end else
}//end hasRecords
public RecordEnumeration select(RMSFilterStartsWith filter,
RMSOrder comparator)
{
RecordEnumeration recordEnumeration = null;
try
{
recordEnumeration = recordStore.enumerateRecords(filter,
comparator,
false);
}//end try
catch(Exception e)
{
System.out.println("Could not create RecordEnumeration " +
e.toString());
}//end catch
return recordEnumeration;
}//end select
public void close()
{
try
{
recordStore.closeRecordStore();
}//end try
catch( Exception e ){
System.out.println("Could not close record store... "+ e.toString() );
}//end catch
}//end close
public void destroy()
{
try
{
close();
RecordStore.deleteRecordStore(id);
}//end try
catch( Exception e )
{
System.out.println("Could not delete record store... " + e.toString() );
}//end catch
}//end deleteRecordStore
}//end MyRecordStore
_________________________________________________________________
//@author Paola González
package rms;
import javax.microedition.rms.RecordEnumeration;
public class PalabraSignificadoRMS
{
// RMS (Record Management System)
private MyRecordStore palabrasDB;
private MyRecordStore significadoDB;
// an object representing a recordPalabra filter
private RMSFilterStartsWith filter;
// an object representing the recordPalabra order criteria
private RMSOrder comparator;
// the id of the recordPalabra store
private String recordStoreIdPalabra;
private String recordStoreIdSignificado;
// constructor
public PalabraSignificadoRMS()
{
recordStoreIdPalabra = "Palabra";
recordStoreIdSignificado= "Significado";
// create the recordPalabra store
palabrasDB = new MyRecordStore(recordStoreIdPalabra);
palabrasDB.create();
significadoDB = new MyRecordStore(recordStoreIdSignificado);
significadoDB.create();
// create the recordPalabra store
System.out.println( ">>> Record store: " + recordStoreIdPalabra +
recordStoreIdSignificado+ " has been created." );
insertaPalabrasDB();
insertaSignificadoDB();
}//end constructor
public void insertaPalabrasDB()
{
palabrasDB.addRecord("Innovar");
palabrasDB.addRecord("RID");
palabrasDB.addRecord("MAD");
palabrasDB.addRecord("CSA");
palabrasDB.addRecord("Neuerung");
palabrasDB.addRecord("Twittear");
}//end palabrasDB
public void insertaSignificadoDB()
{
significadoDB.addRecord("Crear algo nuevo,Modificar algo existente que da como resultado algo nuevo");
significadoDB.addRecord("Deposito(RACK) de piezas ");
significadoDB.addRecord("Material Dañado");
significadoDB.addRecord("Control Seguimientos Auditorias");
significadoDB.addRecord("Plataforma de apoyo a las etapas iniciales de innovacion");
significadoDB.addRecord("Escribir algo es twitter");
}
public int getNumberOfRecords()
{
return palabrasDB.getNumberOfRecords();
}
public String getPalabraRecord(int n)
{
return palabrasDB.getRecord(n);
}
public MyRecordStore getPalabraDB()
{
return palabrasDB;
}
public MyRecordStore getSignificadoDB()
{
return significadoDB;
}
public void printRecordsById()
{
int recordId;
String recordPalabra;
String recordSignificado;
try
{
//System.out.println( " " );
//System.out.println( "Number of records: "+ palabrasDB.getNumberOfRecords() );
for( recordId=1;
recordId <= palabrasDB.getNumberOfRecords(); recordId++ ) { recordPalabra = palabrasDB.getRecord(recordId); recordSignificado = significadoDB.getRecord(recordId); System.out.println( "Record ID-"+ recordId +": "+ recordPalabra+":/n"+ recordSignificado); }//end for }//end try catch( Exception e ) { System.err.println( e.toString() ); }//end catch }//end printRecordsById public String[] getRecordsByIdByPalabra() { int recordId; String[] record; record= new String[ palabrasDB.getNumberOfRecords()]; try { for( recordId=1; recordId <= palabrasDB.getNumberOfRecords(); recordId++ ) { record[recordId-1] = palabrasDB.getRecord(recordId); }//end for }//end try catch( Exception e ) { System.err.println( e.toString() ); }//end catch return record; }//end printRecordsByIdByPalabra public String[] getRecordsByIdBySignificado() { int recordId; String[] record; record= new String[ significadoDB.getNumberOfRecords()]; try { for( recordId=1; recordId <= significadoDB.getNumberOfRecords(); recordId++ ) { record[recordId-1] = significadoDB.getRecord(recordId); }//end for }//end try catch( Exception e ) { System.err.println( e.toString() ); }//end catch return record; }//end printRecordsById public void printRecordsByEnumeration(MyRecordStore currentRecordStore) { RecordEnumeration recordEnumeration; String record; try { System.out.println( "Number of records: "+ currentRecordStore.getNumberOfRecords() ); if(currentRecordStore.hasRecords()) { //creates the filter starts with... filter = new RMSFilterStartsWith("P"); //creates the order criteria comparator = new RMSOrder(false); recordEnumeration = currentRecordStore.select(filter, comparator); // inserts one more recordPalabra after the select //palabrasDB.addRecord("The red thin line"); // prints the records according to the filter and order while( recordEnumeration.hasNextElement() ) { record = new String( recordEnumeration.nextRecord() ); System.out.println( "Record: "+ record); }//end while //then destroy the enumeration, releasing resources recordEnumeration.destroy(); } }//end try catch( Exception e ) { System.out.println( e.toString() ); }//end catch }//end printRecordsByEnumeration }//end PalabraSignificadoRMS ____________________________________________________________________________________ /** * RMSFilterStartsWith * @author Gerardo Ayala * November 2009 */ package rms; import javax.microedition.rms.*; public class RMSFilterStartsWith implements RecordFilter { String subString; // constructor public RMSFilterStartsWith(String aSubstring) { subString = aSubstring; }//end constructor public boolean matches(byte[] recordContentBytes) { String recordContent; recordContent = new String(recordContentBytes); if (recordContent.startsWith(subString)) { return true; }//end if else { return false; }//end else }//end matches }// end RMSFilterStartsWith _____________________________________________________________________________________ package rms; /** * RMSOrder * @author Gerardo Ayala * November 2009 */ import javax.microedition.rms.*; public class RMSOrder implements RecordComparator { boolean isAscendingOrder; // constructor public RMSOrder(boolean isAscendingOrderIndicator) { isAscendingOrder = isAscendingOrderIndicator; }//end RMSOrder public int compare(byte[] recordContentBytes1, byte[] recordContentBytes2) { String recordContent1; String recordContent2; recordContent1 = new String(recordContentBytes1); recordContent2 = new String(recordContentBytes2); if (isAscendingOrder) { if ((recordContent1.compareTo(recordContent2)) > 0)
{
return (RecordComparator.FOLLOWS);
}//end if
else
{
if ((recordContent1.compareTo(recordContent2)) <> 0)
{
return (RecordComparator.PRECEDES);
}//end if
else
{
return (RecordComparator.EQUIVALENT);
}//end else
}//end else
}//end else
}//end compare
}//end classRMSOrder
No hay comentarios.:
Publicar un comentario