What you are planning is just fine: you can have phones listen on sockets too. If you just want to have peer-to-peer communication and are more interested in the application you're writing, you might want to take a look at JXTA, which is a somewhat popular P2P system for Java. I don't know it, and I've heard some bad things about its performance, but for your application it could be suitable.
But it's not very hard to roll your own, either. However, I haven't seen any HTTP server-side libraries for Java ME, so using HTTP might be more work than necessary. I would probably just implement a custom protocol over TCP sockets, since it does not appear you would need to be interoperable with anything already in existence.
Socket communication in Java ME is through the Generic Connection Framework, found in the javax.microedition.io
package, and from the client side it's exactly like using HTTP connections, i.e., something like
String url = "socket://192.168.xxx.xxx:12345";
SocketConnection conn = (SocketConnection) Connector.open(url);
And then you can get an InputStream
and OutputStream
for the connection from that, or DataInputStream
and DataOutputStream
if you want to send binary data.
On the server side you would do
String url = "socket://:12345";
ServerSocketConnection sock = (ServerSocketConnection) Connector.open(url);
SocketConnection conn = (SocketConnection) sock.acceptAndOpen();
The acceptAndOpen
blocks until a connection is made, so if it is important for the server to be doing something else, make sure to put the connection acceptance into its own thread.
A caveat: when I was doing this a few years back, I found out that just listening on a socket does not turn on the network on all phones, so even though the server began listening, it was not possible to connect to it because it was not on the network. The way I worked around it was to open the Web browser on the phone, but any client opening a socket is enough, so you could also do it from the application by trying to open a client connection yourself.
There is also something called the Push Registry. When you create your Midlet, there is a possibility to register the application with a MIDlet-Push
attribute in the JAD file, so that you don't have to have your application running but the system will wake it up when a connection is attempted on a certain port. I've never actually implemented this, so I cannot give any more advice on it.