I am new to Threads. I am trying to broadcast message from the server to clients.but I cannot. It seems like the server is always listen to a new connection.But I can send m
while (true)
loop.DataInputStream#readLine(...)
as this could be dangerous to do.For example, your main could be as simple as this...
public static void main(String[] args) {
MyServer myServer = new MyServer();
myServer.getThingsRunning();
}
Edit
Note added as a warning: I don't generally work with sockets, serversockets, or create chat programs, and I'm still new at using Executors, but you could structure your code something along these lines...
public class MultiServer implements Runnable {
public static final int PORT_NUMBER = 2222;
private static final int THREAD_POOL_COUNT = 20;
private List clientList = new ArrayList<>();
private ServerSocket serverSocket;
private ExecutorService clientExecutor = Executors.newFixedThreadPool(THREAD_POOL_COUNT);
public MultiServer() throws IOException {
serverSocket = new ServerSocket(PORT_NUMBER);
}
@Override
public void run() {
// embed your socket acceptance loop in a Runnable's run method
while (true) {
try {
Socket clientSocket = serverSocket.accept();
MultiClient client = new MultiClient(clientSocket);
clientList.add(client);
clientExecutor.execute(client);
} catch (IOException e) {
// TODO notify someone of problem!
e.printStackTrace();
}
}
}
// ..... more methods and such
public static void main(String[] args) {
try {
MultiServer multiServer = new MultiServer();
new Thread(multiServer).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}