2008-03-09

HOWTO: SunSPOT socket communication

Upplagd av Mneme

Sockets really seem to be the simplest way to get data from the spot to a desktop application wireless. It's not really as difficult as it seems to start with but it might be a bit messy to start with.

Serversided (to recive data from the spot):
/*Regular ServerSocket. This can of course simply be modified for sending data aswell. Code for stability (handling reconnects on lost connection and so forth I leave to you. Same with the try-blocks.*/
Socket s;
/*ServerSocket(portnumber), portnumber is the port the application will listen on*/
ServerSocket ss = new ServerSocket(4711):
s = ss.accept()
/*Open the InputStream*/
InputStream input = s.getInputStream();
/*Read an integer*/
int in = input.readInt();

Spotsided:
/*To send data to the socket. InputConnection can ofcourse be used to read, for example.*/
OutputConnection connection =
(OutputConnection)Connector.open("socket://127.0.0.1:4711");
OutputStream out = connection.openOutputStream();

/*Write data to the desktop app.*/
out.write(0);
out.flush();

SocketProxy
To run sockets on the SunSpot you need to start up a socket-proxy on the computer you have the basestation connected to. For that you need to run ant so:
1. Locate your ant installation - for mac/*nix users you will most likely already have this in your path so you should be fine. On windows (if you haven't fixed it yourself) you will probably find ant somewhere in your local Eclpise/Netbeans directory.
2. Go to the directory of your spot-application, or more precisely the directory where you have the build.xml (ant buildfile) for spots. Then run:
ant socket-proxy
...and you should be good to go.

0 kommentarer: