|
|
Line 1: |
Line 1: |
| <PRE>
| |
| import java.util.*;
| |
|
| |
|
| public class Server {
| |
|
| |
| private int port;
| |
| private Vector socketVec;
| |
| private ServerDaemon daemon;
| |
|
| |
| /* Constructor Server. */
| |
| public Server(String[] args) {
| |
|
| |
| if (args.length > 0) {
| |
| try {
| |
| port = java.lang.Integer.parseInt(args[0]);
| |
|
| |
| } catch (NumberFormatException e) {
| |
| System.out.println("ERROR: "
| |
| + args[0] + " : " + e.getMessage());
| |
| System.exit(0);
| |
| }
| |
| } else {
| |
| port = 2015; // default value
| |
| }
| |
|
| |
| socketVec = new Vector(50);
| |
| }
| |
|
| |
| // Simply starts the server daemon
| |
| private void startServer() {
| |
| try {
| |
| daemon = new ServerDaemon(this, port);
| |
| } catch (Exception e) {
| |
| e.printStackTrace();
| |
| }
| |
| }
| |
|
| |
| // add a connection to the vector
| |
| public void addMySocket(MyServerSocket s) {
| |
| socketVec.addElement(s);
| |
| }
| |
|
| |
| // remove a connection from vector
| |
| public synchronized void loggedOf(MyServerSocket s) {
| |
| socketVec.removeElement(s);
| |
| }
| |
|
| |
| // method handleMessage
| |
| public synchronized void handleMessage(String line,
| |
| MyServerSocket s) {
| |
|
| |
| if (line.toLowerCase().equals("wwhhoo")) {
| |
| MyServerSocket oth;
| |
| for (int i = 0; i < socketVec.size(); i++) {
| |
| oth = (MyServerSocket) socketVec.elementAt(i);
| |
|
| |
| if (s != oth)
| |
| s.sendMessage(oth.getIP());
| |
| }
| |
|
| |
| } else {
| |
| broadCast(line);
| |
| }
| |
| }
| |
|
| |
| private synchronized void broadCast(String message) {
| |
| MyServerSocket s;
| |
| for (int i = 0; i < socketVec.size(); i++) {
| |
| s = (MyServerSocket) socketVec.elementAt(i);
| |
| s.sendMessage(message);
| |
| }
| |
| }
| |
|
| |
| private void cleaner() {
| |
| long sleepTime = 1000L // milliseconds
| |
| * 60 // seconds
| |
| * 10; // minutes
| |
| while (true) {
| |
| try {
| |
| Thread.sleep(sleepTime);
| |
|
| |
| long compTime =
| |
| System.currentTimeMillis()
| |
| - sleepTime;
| |
|
| |
| for (int i = 0; i < socketVec.size(); ) {
| |
| MyServerSocket s;
| |
| s = (MyServerSocket) socketVec.elementAt(i);
| |
|
| |
| if ( !s.isInactive(compTime)) {
| |
| i++;
| |
| }
| |
| }
| |
|
| |
| } catch (Throwable e) {}
| |
| } // end while
| |
| }
| |
|
| |
| public static void main(String[] args) {
| |
| Server serv = new Server(args);
| |
| serv.startServer();
| |
| serv.cleaner();
| |
| }
| |
| }
| |
| </PRE>
| |
| [[Category:Into Java]]
| |