//----------------------------------------------------------------------------
// Listener implements IpDirectorAvailabilityListener interface
// FILE: IpdListener.java
// Description: Listens on IPD state changed event.
// Once IPD state turns to ACTIVE, 3 local sockets are opened.
//----------------------------------------------------------------------------
package lsockets;
import com.motorola.oem.ipd.IpDirectorAvailabilityListener;
import com.motorola.oem.ipd.LocalSocketManager;
public class IpdListener implements IpDirectorAvailabilityListener {
// 3 sockets:
private ServerSocketTcp sst = null;
private ServerSocketUdp ssd = null;
private ClientSocketTcp cst = null;
static boolean socketsInitialized = false;
public IpdListener() {
System.out.println("MIDlet: IpdListener is initializing...");
// set this class as IPD listener
LocalSocketManager.setIpDirectorListener(this);
if(LocalSocketManager.getIpdState() == LocalSocketManager.IPD_STATE_ACTIVE) {
openSockets();
}
}
// implement handler
public void onIpdStateChanged(int newIpdState) {
System.out.println("IpdListener: IPD State Changed to "+newIpdState);
switch(newIpdState){
case LocalSocketManager.IPD_STATE_ACTIVE:
if(!socketsInitialized){
openSockets();
}
break;
case LocalSocketManager.IPD_STATE_INACTIVE:
if(socketsInitialized){
closeSockets();
}
break;
default :
break;
}
}
// open local sockets
public void openSockets() {
// Open a TCP server thread listening on the local port
sst = new ServerSocketTcp(LocalSocketManager.getListenPort());
// Open a UDP server thread listening on the local port
ssd = new ServerSocketUdp(LocalSocketManager.getListenPort());
// Open a TCP client thread to the external device's IP on port
// 5678(remote server's port).
cst = new ClientSocketTcp(LocalSocketManager.getRemoteAddress(), 5678);
socketsInitialized = true;
}
// close all local sockets
public void closeSockets() {
System.out.println("IpdListener: closeSockets() entered");
if(sst != null ){sst.close(); sst = null;}
if(ssd != null ){ssd.close(); ssd = null;}
if(cst != null ){cst.close(); cst = null;}
socketsInitialized = false;
}
}
|