Monday, December 29, 2008

Connection ? : Datagram

I'm always been very interested in connection in mobile phone, because phone comes handy, most of all my friend have phone and still connected. Now i want to LEARN connection, a Datagram connection. Datagram connection is simpler than Socket, that's what Java Tutorial said.

So.. let's begin.
First, I copied all of class in the WTK2.5.2_01 (C:\WTK2.5.2_01\apps\NetworkDemo\classes\datagram) to BlueJ! (The Readme.txt file also :D )
Compile all, deploy.

As seen in the readme file, "Run two instances of the emulator", "One acts as the datagram server, and the other as the datagram client". So, i click the Deploy button twice, and i get two emulator. After that, i go to the first emulator, and set that as server, and then set the client. I try to send a message to server, and in the server phone, i get the message. And then i try the other way. It Work !

That is the basic connection, i gonna edit them all.

updated!
The first thing that I do is, give the Server a Name !
So, in the Server class, I declare new variable called ServerName, and add new Constructor. Also a method that return the server name.
The variable
..
....

private DatagramMIDlet parent;
private Display display;
private String serverName; /**here*/
private Form f;
private StringItem si;
private TextField tf;
..
..

the new Constructor
..
...
display.setCurrent(f);
}

public Server(DatagramMIDlet m, int p, String name) {
parent = m;
port = p;
serverName = name;
display = Display.getDisplay(parent);
f = new Form(name);
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
...
..

And.. getServerName() method,
public String getServerName()
{
return serverName;
}

I also edited the DatagramMIDlet class, so the server implementing my constructor(look at the commandAction method)
if (name.equals(SERVER)) {
Server server = new Server(this, port,"The Server !");
server.start();
} else {
Client client = new Client(this, port);
client.start();
}

Compile, Deploy, try becoming the Server, see what i have been changed ? :)

updated!
I have been edited many code of the server and client class
because of to much, i copy paste it directly

first, the server class

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

public class Server implements Runnable, CommandListener {

private DatagramMIDlet parent;
private Display display;
private String serverName;
private Form f;
private TextField tf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
Sender sender;
private String address;
private int port;

..
......
...

public Server(DatagramMIDlet m, int p, String name) {
parent = m;
port = p;
serverName = name;
display = Display.getDisplay(parent);
f = new Form(name);
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}

....
.......
....

public void run() {
String portString = String.valueOf(port);
try {
f.insert(1,new StringItem("Waiting for connection on port"+portString,""));/**here*/
DatagramConnection dc = (DatagramConnection) Connector.open("datagram://:" + portString);

sender = new Sender(dc);

while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);
address = dg.getAddress();
f.insert(1,new StringItem(address+" : ",new String(dg.getData(), 0, dg.getLength())));/**here*/
}
} catch (IOException ioe) {
Alert a = new Alert("Server", "Port " + portString
+ " is already taken.", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} catch (Exception e) {
e.printStackTrace();
}
}

public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
if (address == null) {
f.insert(3,new StringItem("Ooops! ","No destination address")); /**here*/
} else {
sender.send(address, tf.getString()); /**here*/
f.insert(1,new StringItem("Me(Server) : ",tf.getString()));/**here*/
tf.setString("");/**here*/
}
}

public String getServerName()
{
return serverName;
}

public String[] breakString(String s)
{
char[] ca = s.toCharArray();
String[] sa = {};
int h = 0;

for(int w = 0;w <= ca.length-1;w++)
{
if(ca.equals(" "))
{
h = h + 1;
}
else
{
sa[h] = sa[h]+ca[w];
}
}
return sa;
}

}

The Client class

import java.io.IOException;

import javax.microedition.io.*;
import javax.microedition.lcdui.*;


public class Client implements Runnable, CommandListener {
private DatagramMIDlet parent;
private int port;
private String ip; /**here*/
private Display display;
private Form f;
private TextField tf;

private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);

Sender sender;

..
...
...

public Client(DatagramMIDlet m, int p, String IP) {
parent = m;
port = p;
this.ip = IP; /**here*/
display = Display.getDisplay(parent);
f = new Form("Datagram Client");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
..
...
...
public void run() {
String portString = String.valueOf(port);
try {
DatagramConnection dc = (DatagramConnection) Connector.open("datagram://"+ip+":" + portString); /**here*/

f.insert(1,new StringItem("Waiting for connection "+ip+" on port "+portString,""));/**here*/

sender = new Sender(dc);

while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);

// Have we actually received something or
// is this just a timeout ?
if (dg.getLength() > 0) {
f.insert(1,new StringItem("Server : ",new String(dg.getData(), 0, dg.getLength()))); /**here*/
}
}
} catch (ConnectionNotFoundException cnfe) {
....
.....
..
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(null, tf.getString());
f.insert(1,new StringItem("Me(Client) : ",tf.getString()));/**here*/
tf.setString("");/**here*/
}

if (c == exitCommand) {
parent.destroyApp(true);
parent.notifyDestroyed();
}
}

public void stop() {
}

}

And the DatagramMIDlet class

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class DatagramMIDlet extends MIDlet implements CommandListener {

private static final int DEFAULT_PORT = 5555;
private String IP_ADDRESS;
private static final String DEFAULT_IP = "202.3.213.129";
private static final String SERVER = "Server";
private static final String CLIENT = "Client";
private static final String[] names = { SERVER, CLIENT };
private static Display display;
private Form f;
private ChoiceGroup cg;
private TextField portField;
private TextField ipField; /**here*/
private boolean isPaused;
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command startCommand = new Command("Start", Command.ITEM, 1);

public DatagramMIDlet() {
display = Display.getDisplay(this);
f = new Form("Datagram Demo");
cg = new ChoiceGroup("Please select peer", Choice.EXCLUSIVE, names,null);
f.append(cg);
portField = new TextField("Port number:", String.valueOf(DEFAULT_PORT),6, TextField.NUMERIC);
ipField = new TextField("IP address:", DEFAULT_IP,20, TextField.ANY);/**here*/
f.append(ipField);/**here*/
f.append(portField);

....
........
......

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == startCommand) {
String name = cg.getString(cg.getSelectedIndex());
int port = Integer.parseInt(portField.getString());
String ip = ipField.getString(); /**here*/

if (name.equals(SERVER)) {
Server server = new Server(this, port,"The Server");/**here*/
server.start();
} else {
Client client = new Client(this, port, ip);
client.start();
}
}
}
}

2 comments:

  1. 1st Prizes: A Nintendo Wii games console
    School Under 16 ?!!

    *applause*
    congratulation...

    nice blog, ;-)

    ReplyDelete