1 package fr.ove.clientserver;
2
3 import java.net.Socket;
4 import java.io.IOException;
5 import java.util.TooManyListenersException;
6 import fr.ove.clientserver.SocketServer;
7 import fr.ove.clientserver.events.*;
8 import fr.ove.utils.Connection;
9 import fr.ove.utils.ConnectionHandler;
10
11 /***
12 * A server.<BR>
13 * After its instanciation, don't forget to set the connection handler. Otherwise,
14 * clients could not connect.
15 */
16 public class Server implements SocketServerListener {
17 /***
18 * The socket server.
19 */
20 private SocketServer socketServer;
21
22 /***
23 * The connection handler for the server.
24 */
25 private ConnectionHandler handler;
26
27 /***
28 * The default constructor.<BR>
29 * The default is the server running on port 6666 and allowing a
30 * maximum of 300 connections.
31 */
32 public Server() throws IOException {
33 this(6666, 300);
34 }
35
36 /***
37 * The constructor.
38 * @param portNumber the port number used on the host to run the server.
39 * @param maxSocket the maximum number of connections allowed.
40 */
41 public Server(int portNumber, int maxConnection) throws IOException {
42 socketServer = new SocketServer(portNumber, maxConnection);
43 try {
44 socketServer.addSocketServerListener(this);
45 }
46 catch (TooManyListenersException tmle) {
47 tmle.printStackTrace();
48 }
49 }
50
51 /***
52 * Sets the connection handler for the server.
53 * @param handler the connection handler.
54 */
55 public void setConnectionHandler(ConnectionHandler handler) {
56 this.handler = handler;
57 }
58
59 /***
60 * Returns the connection handler of the server.
61 */
62 public ConnectionHandler getConnectionHandler() {
63 return handler;
64 }
65
66
67
68 /***
69 * Accept the socket encapsulated inside the event fired by the socket server listenned.
70 * @param evt the event fired by the socket server listenned.
71 */
72 public void socketAccepted(SocketServerEvent evt) {
73 Socket socket = evt.getSocket();
74 if (handler != null) {
75 Connection connection = new Connection();
76 try {
77 connection.open(socket);
78 handler.handleConnection(connection);
79 }
80 catch (IOException ioe) {
81 System.out.println("Failed to open the connection");
82 ioe.printStackTrace();
83 }
84 }
85 else {
86 try {
87 socket.close();
88 }
89 catch (IOException ioe) {
90 System.out.println("Failed to close the socket");
91 ioe.printStackTrace();
92 }
93 }
94 }
95 }