I wrote a server-client communication program and it worked well.
import java.io.*;
import java.net.*;
class Client {
public sta
MainServer class
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(2343);
} catch (IOException e) {
System.err.println("Could not listen on port: 2343");
}
while(listeningSocket){
Socket clientSocket = serverSocket.accept();
MiniServer mini = new MiniServer(clientSocket);
mini.start();
}
serverSocket.close();
}
}
Helper Class
public class MiniServer extends Thread{
private Socket socket = null;
public MiniServer(Socket socket) {
super("MiniServer");
this.socket = socket;
}
public void run(){
//Read input and process here
}
//implement your methods here
}
Well, when I do something like that, I implement a listener that manages the server side, so when a client (the client won't probably need changes) connects, the server launch one thread to work with that client.
while (!stop)
{
socket = serverSocket.accept();
HiloSocket hiloSocket = new HiloSocket(socket, this);
hiloSocket.start();
}
Of course, HiloSocket extends Thread and it has the logic behind to manage the client...
You want to look into Java concurrency. That's the concept of one Java program doing multiple things at once. At a high level you will be taking your while(true) { //... }
block and running it as part of the run()
method of a class implementing Runnable. You'll create instances of Thread that invoke that run()
method, probably one per client you expect.
For a really good, deep understanding of all that Java offers when it comes to concurrency, check out Java Concurrency in Practice.