Program-program
yang dibutuhkan untuk mengolah aplikasi java antara lain :
1. JDK
(Java Development Kit).Bisa didownload di situs resmi Oracle http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Sun Java
(TM) Wireless Toolkit
2.5.2_01 for CLDC. Bisa di download di http://www.oracle.com/technetwork/java/download-135801.html
3. Notepad++
, untuk mengedit source code program. Bisa di download di http://www.filehippo.com/download_notepad/
Setelah
semua di download, install semua program diatas.
MembuatAplikasi
Java Network Demo
Demo ini memiliki dua MIDlets: SocketDemo dan
DatagramDemo. Setiap demo membutuhkan
Anda untuk menjalankan dua contoh emulator sehingga Anda dapat mensimulasikan hubungan server dan client
Anda untuk menjalankan dua contoh emulator sehingga Anda dapat mensimulasikan hubungan server dan client
Pada
laporan ini, kita akan mempelajari bagaimana cara membuat aplikasi NetworkDemo
tersebut. Langkah-langkahnya sebagai berikut :
1. Jalankan program Wireless Toolkit
6. Akan muncul tampilan yang
menandakan project kita berhasil dibuat.
Source Code Program
1. Datagram
a.
Client
package datagram;
importjava.io.IOException;
importjavax.microedition.io.ConnectionNotFoundException;
importjavax.microedition.io.Connector;
importjavax.microedition.io.Datagram;
importjavax.microedition.io.DatagramConnection;
importjavax.microedition.lcdui.Alert;
importjavax.microedition.lcdui.AlertType;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.StringItem;
importjavax.microedition.lcdui.TextField;
public class Client implements Runnable, CommandListener {
privateDatagramMIDlet parent;
privateint port;
private Display display;
private Form f;
privateStringItemsi;
privateTextFieldtf;
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) {
parent = m;
port = p;
display =
Display.getDisplay(parent);
f = new
Form("Datagram Client");
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);
}
public void start() {
Thread t = new
Thread(this);
t.start();
}
public void run() {
String
portString = String.valueOf(port);
try {
DatagramConnection
dc = (DatagramConnection) Connector
.open("datagram://localhost:" +
portString);
si.setText("Connected
to server on port "+portString);
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) {
si.setText("Message
received - "
+ new String(dg.getData(), 0,
dg.getLength()));
}
}
} catch
(ConnectionNotFoundExceptioncnfe) {
Alert a = new Alert("Client",
"Please run Server MIDlet first on
port " + portString,
null,
AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
} catch
(IOExceptionioe) {
ioe.printStackTrace();
}
}
public void commandAction(Command c, Displayable s) {
if ((c ==
sendCommand) && !parent.isPaused()) {
sender.send(null,
tf.getString());
}
if (c ==
exitCommand) {
parent.destroyApp(true);
parent.notifyDestroyed();
}
}
public void stop() {
}
}
Setelahselesai, simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\datagram\Client.java
b.
DatagramMIDlet
package
datagram;
importjavax.microedition.lcdui.Choice;
importjavax.microedition.lcdui.ChoiceGroup;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.TextField;
importjavax.microedition.midlet.MIDlet;
public
class DatagramMIDlet extends MIDlet implements CommandListener {
private
static final int DEFAULT_PORT = 5555;
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;
privateChoiceGroup
cg;
privateTextFieldportField;
privatebooleanisPaused;
private
Command exitCommand = new Command("Exit", Command.EXIT, 1);
private
Command startCommand = new Command("Start", Command.ITEM, 1);
publicDatagramMIDlet()
{
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);
f.append(portField);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public
static Display getDisplay() {
return display;
}
publicbooleanisPaused()
{
returnisPaused;
}
public
void startApp() {
isPaused = false;
}
public
void pauseApp() {
isPaused = true;
}
public
void destroyApp(boolean unconditional) {
}
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());
if (name.equals(SERVER)) {
Server server =
new Server(this, port);
server.start();
} else {
Client client =
new Client(this, port);
client.start();
}
}
}
}
Setelahselesai, simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\datagram\DatagramMIDlet.java
c. Sender
package
datagram;
importjavax.microedition.io.Datagram;
importjavax.microedition.io.DatagramConnection;
public
class Sender extends Thread {
privateDatagramConnection
dc;
private
String address;
private
String message;
public
Sender(DatagramConnection dc) {
this.dc = dc;
start();
}
public
synchronized void send(String addr, String msg) {
address = addr;
message = msg;
notify();
}
public
synchronized void run() {
while (true) {
// If no client to deal, wait until one connects
if (message == null) {
try {
wait();
} catch
(InterruptedException e) {
}
}
try {
byte[] bytes =
message.getBytes();
Datagram dg = null;
// Are we a sender
thread for the client ? If so then there's
// no address parameter
if (address == null) {
dg =
dc.newDatagram(bytes, bytes.length);
} else {
dg =
dc.newDatagram(bytes, bytes.length, address);
}
dc.send(dg);
} catch (Exception ioe) {
ioe.printStackTrace();
}
// Completed client handling, return handler to pool and
// mark for wait
message = null;
}
}
}
Setelahselesai, simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\datagram\Sender.java
d. Server
package
datagram;
importjava.io.IOException;
importjavax.microedition.io.Connector;
importjavax.microedition.io.Datagram;
importjavax.microedition.io.DatagramConnection;
importjavax.microedition.lcdui.Alert;
importjavax.microedition.lcdui.AlertType;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.StringItem;
importjavax.microedition.lcdui.TextField;
public
class Server implements Runnable, CommandListener {
privateDatagramMIDlet
parent;
private
Display display;
private
Form f;
privateStringItemsi;
privateTextFieldtf;
private
Command sendCommand = new Command("Send", Command.ITEM, 1);
private
Command exitCommand = new Command("Exit", Command.EXIT, 1);
Sender sender;
private
String address;
privateint
port;
public
Server(DatagramMIDlet m, int p) {
parent = m;
port = p;
display = Display.getDisplay(parent);
f = new Form("Datagram
Server");
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);
}
public
void start() {
Thread t = new Thread(this);
t.start();
}
public
void run() {
String portString =
String.valueOf(port);
try {
si.setText("Waiting for connection
on port "+portString);
DatagramConnection dc =
(DatagramConnection) Connector
.open("datagram://:" +
portString);
sender = new Sender(dc);
while (true) {
Datagram dg =
dc.newDatagram(100);
dc.receive(dg);
address =
dg.getAddress();
si.setText("Message
received - "
+ new
String(dg.getData(), 0, dg.getLength()));
}
} catch (IOExceptionioe) {
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) {
si.setText("No
destination address");
} else {
sender.send(address,
tf.getString());
}
}
if ((c == Alert.DISMISS_COMMAND) || (c
== exitCommand)) {
parent.destroyApp(true);
parent.notifyDestroyed();
}
}
public
void stop() {
}
}
Setelahselesai, simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\datagram\Server.java
a. Client
package
socket;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjavax.microedition.io.ConnectionNotFoundException;
importjavax.microedition.io.Connector;
importjavax.microedition.io.SocketConnection;
importjavax.microedition.lcdui.Alert;
importjavax.microedition.lcdui.AlertType;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.StringItem;
importjavax.microedition.lcdui.TextField;
public
class Client implements Runnable, CommandListener {
privateSocketMIDlet
parent;
private
Display display;
private
Form f;
privateStringItemsi;
privateTextFieldtf;
privateboolean
stop;
private
Command sendCommand = new Command("Send", Command.ITEM, 1);
private
Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream
is;
OutputStreamos;
SocketConnectionsc;
Sender sender;
privateint
port;
public
Client(SocketMIDlet m, int p) {
parent = m;
port = p;
display = Display.getDisplay(parent);
f = new Form("Socket Client");
si = new StringItem("Status:",
" ");
tf = new TextField("Send:",
"", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.addCommand(sendCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
/**
* Start the client thread
*/
public
void start() {
Thread t = new Thread(this);
t.start();
}
public
void run() {
String portString =
String.valueOf(port);
try {
sc = (SocketConnection)
Connector.open("socket://localhost:"
+ portString);
si.setText("Connected to server on
port "+portString);
is = sc.openInputStream();
os = sc.openOutputStream();
// Start the thread for sending messages - see Sender's main
// comment for explanation
sender = new Sender(os);
// Loop forever, receiving data
while (true) {
StringBuffersb = new
StringBuffer();
int c = 0;
while (((c = is.read())
!= '\n') && (c != -1)) {
sb.append((char) c);
}
if (c == -1) {
break;
}
// Display message to
user
si.setText("Message
received - " + sb.toString());
}
stop();
si.setText("Connection closed");
f.removeCommand(sendCommand);
} catch
(ConnectionNotFoundExceptioncnfe) {
Alert a = new Alert("Client",
"Please run Server MIDlet first on
port " + portString,
null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} catch (IOExceptionioe) {
if (!stop) {
ioe.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public
void commandAction(Command c, Displayable s) {
if ((c == sendCommand) &&
!parent.isPaused()) {
sender.send(tf.getString());
}
if ((c == Alert.DISMISS_COMMAND) || (c
== exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
}
}
/**
* Close all open streams
*/
public
void stop() {
try {
stop = true;
if (sender != null) {
sender.stop();
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
} catch (IOExceptionioe) {
}
}
}
Setelahselesai,
simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\socket\Client.java
b. Sender
package
socket;
importjava.io.IOException;
importjava.io.OutputStream;
public
class Sender extends Thread {
privateOutputStreamos;
private
String message;
public
Sender(OutputStreamos) {
this.os = os;
start();
}
public
synchronized void send(String msg) {
message = msg;
notify();
}
public
synchronized void run() {
while (true) {
// If no client to deal, wait until one connects
if (message == null) {
try {
wait();
} catch
(InterruptedException e) {
}
}
if (message == null) {
break;
}
try {
os.write(message.getBytes());
os.write("\r\n".getBytes());
} catch (IOExceptionioe) {
ioe.printStackTrace();
}
// Completed client handling, return handler to pool and
// mark for wait
message = null;
}
}
public
synchronized void stop() {
message = null;
notify();
}
}
Setelahselesai,
simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\socket\Sender.java
c. Server
package
socket;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjavax.microedition.io.Connector;
importjavax.microedition.io.ServerSocketConnection;
importjavax.microedition.io.SocketConnection;
importjavax.microedition.lcdui.Alert;
importjavax.microedition.lcdui.AlertType;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.StringItem;
importjavax.microedition.lcdui.TextField;
public
class Server implements Runnable, CommandListener {
privateSocketMIDlet
parent;
private
Display display;
private
Form f;
privateStringItemsi;
privateTextFieldtf;
privateboolean
stop;
private
Command sendCommand = new Command("Send", Command.ITEM, 1);
private
Command exitCommand = new Command("Exit", Command.EXIT, 1);
InputStream
is;
OutputStreamos;
SocketConnectionsc;
ServerSocketConnectionscn;
Sender sender;
privateint
port;
public
Server(SocketMIDlet m, int p) {
parent = m;
port = p;
display = Display.getDisplay(parent);
f = new Form("Socket Server");
si = new StringItem("Status:",
" ");
tf = new TextField("Send:",
"", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
public
void start() {
Thread t = new Thread(this);
t.start();
}
public
void run() {
String portString =
String.valueOf(port);
try {
si.setText("Waiting for connection
on port "+portString);
scn = (ServerSocketConnection)
Connector.open("socket://:"
+ portString);
// Wait for a connection.
sc = (SocketConnection)
scn.acceptAndOpen();
si.setText("Connection
accepted");
is = sc.openInputStream();
os = sc.openOutputStream();
sender = new Sender(os);
// Allow sending of messages only after Sender is created
f.addCommand(sendCommand);
while (true) {
StringBuffersb = new
StringBuffer();
int c = 0;
while (((c = is.read())
!= '\n') && (c != -1)) {
sb.append((char) c);
}
if (c == -1) {
break;
}
si.setText("Message
received - " + sb.toString());
}
stop();
si.setText("Connection is
closed");
f.removeCommand(sendCommand);
} catch (IOExceptionioe) {
if (ioe.getMessage().equals("ServerSocket
Open")) {
Alert a = new
Alert("Server", "Port " + portString
+ "
is already taken.", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} else {
if (!stop) {
ioe.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public
void commandAction(Command c, Displayable s) {
if ((c == sendCommand) &&
!parent.isPaused()) {
sender.send(tf.getString());
}
if ((c == Alert.DISMISS_COMMAND) || (c
== exitCommand)) {
parent.notifyDestroyed();
parent.destroyApp(true);
}
}
/**
* Close all open streams
*/
public
void stop() {
try {
stop = true;
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (sc != null) {
sc.close();
}
if (scn != null) {
scn.close();
}
} catch (IOExceptionioe) {
}
}
}
Setelahselesai,
simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\socket\Server.java
d. SocketMIDlet
package
socket;
importjavax.microedition.lcdui.Choice;
importjavax.microedition.lcdui.ChoiceGroup;
importjavax.microedition.lcdui.Command;
importjavax.microedition.lcdui.CommandListener;
importjavax.microedition.lcdui.Display;
importjavax.microedition.lcdui.Displayable;
importjavax.microedition.lcdui.Form;
importjavax.microedition.lcdui.TextField;
importjavax.microedition.midlet.MIDlet;
public
class SocketMIDlet extends MIDlet implements CommandListener {
private
static final int DEFAULT_PORT = 5000;
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;
privateChoiceGroup
cg;
privatebooleanisPaused;
privateTextFieldportField;
private
Server server;
private
Client client;
private
Command exitCommand = new Command("Exit", Command.EXIT, 1);
private
Command startCommand = new Command("Start", Command.ITEM, 1);
publicSocketMIDlet()
{
display = Display.getDisplay(this);
f = new Form("Socket 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);
f.append(portField);
f.addCommand(exitCommand);
f.addCommand(startCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
publicbooleanisPaused()
{
returnisPaused;
}
public
void startApp() {
isPaused = false;
}
public
void pauseApp() {
isPaused = true;
}
public
void destroyApp(boolean unconditional) {
if (server != null) {
server.stop();
}
if (client != null) {
client.stop();
}
}
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());
if (name.equals(SERVER)) {
server = new
Server(this, port);
server.start();
} else {
client = new
Client(this, port);
client.start();
}
}
}
}
Setelahselesai,
simpandengan format
C:\Users\NamaUser\j2mewtk\2.5.2\apps\NetworkDemo\src\socket\SocketMIDlet.java
4. UjiCoba Program
5. Kesimpulan
·
Java merupakan bahasa pemrograman
yang banyak digunakan pada aplikasi mobile
·
Sebelum membuat program Java,
pastikan komputer sudah terinstall JDK (Java Development Kit)
·
Sun
JavaWireless Toolkit, adalah salahsatu program yang bisa digunakan untuk
membuat aplikasi Java.
·
Fungsi network demo adalah untuk
mensimulasikan hubungan server
dan client
·
Source program akanotomatistersimpan
di direktori
C:\Users\NamaUser \j2mewtk\2.5.2\apps\NamaProject\src\
·
Hasil program berupa file “.jad” dan
“.jar”
Posted by , Published at 11.41 and have
0
komentar



Tidak ada komentar:
Posting Komentar