Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sockets and Processes in Java

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 ?

like image 743
daentech Avatar asked Dec 03 '22 16:12

daentech


1 Answers

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
}
like image 157
basszero Avatar answered Dec 11 '22 08:12

basszero