In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.
Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?
In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?
If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into SocketChannels
and/or NIO async sockets / selectors. This should get you started.
boolean finished = false;
int port = 10000;
ServerSocket server = new ServerSocket(port);
while (!finished) {
// This will block until a connection is made
Socket s = server.accept();
// Spawn off some thread (or use a thread pool) to handle this socket
// Server will continue to listen
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With