Show NetworkServer.java syntax highlighted
package persister.network;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import persister.Message;
import persister.distributed.ServerCommunicator;
/*
*
* */
public class NetworkServer extends Thread{
private ServerContext context;
private ServerSocket socket;
private ArrayList<ServerThreadWorker> clients = new ArrayList<ServerThreadWorker>();
public NetworkServer(int port, ServerCommunicator communicator) throws Exception{
this.context = buildContext(port);
this.context.setCommunicator(communicator);
openServerSocket();
start();
}
public void run(){
listen();
}
public ServerContext buildContext(int port){
ServerContext context = new ServerContext();
context.setPort(port);
return context;
}
public void openServerSocket() throws Exception{
socket = new ServerSocket(context.getPort());
}
public void listen() {
while(true){
try{
clients.add(new ServerThreadWorker(context, socket.accept()));
}catch(SocketException e){
break;
}catch(Exception e){
// ignore bad connection attempt and listen for another one.
e.printStackTrace();
}
}
}
/**
* designed to be called on the same thread that creates the server.
* @param msg
*/
public void send(Message msg){
for(ServerThreadWorker client: clients){
try{
client.sendMessage(msg);
}catch(Exception e){
//remove the client if there is a problem communicating
clients.remove(client);
}
}
}
public void kill(){
try {
this.socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
See more files for this project here