Simples chat ponto-a-ponto NFCIP
Dados do artigo
Artigo
Tradução:
Originado de Simple NFCIP peer to peer chat
Por valderind4
Última alteração feita por hamishwillee
em 19 Dec 2011
Exemplo de uma comunicação P2P NFCIP no Nokia 6131 NFC. O usuário pode trocar mensagens com outro aparelho, teclando. Por padrão o MIDlet está no estado de leitura e quando o usuário quer escrever alguma coisa o MIDlet vai para o estado de escrita.
Note que a classe NFCIPConnection usada neste exemplo é implementação própria para o Nokia 6131 NFC, sendo assim este exemplo pode não funcionar em outros aparelhos.
package com.nokia.nfc.sample.app;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.nokia.nfc.p2p.NFCIPConnection;
/* Example of P2P communication in Nokia 6131 NFC. User can exchange messages
* with other phones by touching them. By default MIDlet is in reading state and
* when user wants to write something MIDlet goes to writing state.
*/
public class P2PChat extends MIDlet implements Runnable, CommandListener {
// Initiator URL, used to make the connection to other phone
private static final String INITIATOR_URL="nfc:rf;type=nfcip;mode=initiator";
// Target URL, used to listen for incoming connections
private static final String TARGET_URL = "nfc:rf;type=nfcip;mode=target";
// UI elements
private Display display;
private Form form;
private TextBox writeTb;
// Commands
private Command writeCmd;
private Command cancelCmd;
private Command exitCmd;
// Is the MIDlet in reading or writing state
boolean reading = true;
// MIDlet UI initialization and starting the thread
protected void startApp() throws MIDletStateChangeException {
// Initialize UI
display = Display.getDisplay(this);
form = new Form("Form");
writeCmd = new Command("Write", Command.ITEM, 1);
cancelCmd = new Command("Cancel", Command.CANCEL, 1);
exitCmd = new Command("Exit", Command.EXIT, 1);
form.addCommand(writeCmd);
form.addCommand(exitCmd);
form.setCommandListener(this);
display.setCurrent(form);
// Start the thread
Thread thread = new Thread(this);
thread.start();
}
// Thread to exchange data between phones
public void run() {
NFCIPConnection conn = null;
// Reading state
if (reading) {
// Read while in reading state
while (reading) {
try {
// Start waiting for other phone to initiate connection,
// blocks until connection made or another NFCIP connection
// open called
conn = (NFCIPConnection) Connector.open(TARGET_URL);
// Receive data from connection
byte[] data = conn.receive();
// Send empty message to connection
conn.send(null);
// Append received string to form
form.append(">> " + new String(data) + "\n");
// Close connection
conn.close();
} catch (Exception ex) {
try {
if (conn != null) {
conn.close();
}
} catch (IOException e) {
}
}
}
// Writing state
} else {
// Write while in writing state. If writing fails MIDlet will do the
// writing loop until it succeeds or changed back to reading state.
while (!reading) {
try {
// Try to connect another phone, blocks until connection
// made or another NFCIP connection open called
conn = (NFCIPConnection) Connector.open(INITIATOR_URL);
// Send string from TextBox to connection
conn.send(writeTb.getString().getBytes());
// Receive reply
conn.receive();
// Append sent message to form
form.append("<< " + writeTb.getString() + "\n");
// Close connection
conn.close();
display.setCurrent(form);
read();
} catch (Exception ex) {
try {
if (conn != null) {
conn.close();
}
} catch (IOException e) {
}
}
}
}
}
public void commandAction(Command c, Displayable d) {
if (c == writeCmd && d == form) {
writeTb();
} else if (c == writeCmd && d == writeTb) {
write();
} else if (c == cancelCmd) {
read();
} else if (c == exitCmd) {
notifyDestroyed();
}
}
// Go to read state
private void read() {
reading = true;
display.setCurrent(form);
// Start new thread that kills the current connection
Thread thread = new Thread(this);
thread.start();
}
// Display TextBox
private void writeTb() {
writeTb = new TextBox("Text to write", null, 255, TextField.ANY);
writeTb.addCommand(writeCmd);
writeTb.addCommand(cancelCmd);
writeTb.setCommandListener(this);
display.setCurrent(writeTb);
}
// Go to write state
private void write() {
reading = false;
// Show alert
Alert a = new Alert("Writing", "Touch to write", null, AlertType.INFO);
a.addCommand(cancelCmd);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
// Start new thread that kills the current connection
Thread thread = new Thread(this);
thread.start();
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
}


Hi, Sorry, but i copied this code and i tested it first with NFC6131 emulator : it does not work. I tested it also on an NFC nokia 6131 phone, and it does not work. Have any one tested this code snapet ?? Any suggestion will strongly help me. Thanks a lot !!