package server.Network;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import CustomEvents.CustomEventSource;
import CustomEvents.ICustomEventListener;
import chatown.Client;
import chatown.Globals;
public class CT_ServerSocket implements Runnable {
private CustomEventSource[] _events = new CustomEventSource[3];
private ServerSocket _serversocket;
private Socket _socket;
private Map<String, Client> _clientsMap = Collections.synchronizedMap(new HashMap<String, Client>()); // key - client ID
private Map<String, CT_Socket> _clientsSocketMap = Collections.synchronizedMap(new HashMap<String, CT_Socket>()); // key - client ID
public CT_ServerSocket() {
_events[Globals.CONNECT] = new CustomEventSource();
_events[Globals.DISCONNECT] = new CustomEventSource();
_events[Globals.OPEN_MSG] = new CustomEventSource();
}
public void registerConnectClientEvent(ICustomEventListener listener) {
_events[Globals.CONNECT].addEventListener(listener);
}
public void registerDisconnectClientEvent(ICustomEventListener listener) {
_events[Globals.DISCONNECT].addEventListener(listener);
}
public void registerOpenMsgClientEvent(ICustomEventListener listener) {
_events[Globals.OPEN_MSG].addEventListener(listener);
}
public void connect(int port) {
if(_serversocket != null)
{
try {
_serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
_serversocket = null;
}
try {
_serversocket = new ServerSocket(port);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error in server connection");
e.printStackTrace();
}
}
public void disconnect() {
if(_serversocket != null)
{
try {
_serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
_serversocket = null;
}
}
@Override
public void run() {
while (true) {
if (_serversocket == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) { e.printStackTrace(); }
} else {
try {
_socket = _serversocket.accept();
CT_ClientSocket clientSocket = new CT_ClientSocket(_events, _socket, _clientsMap, _clientsSocketMap);
Thread t = new Thread(clientSocket);
t.start();
} catch (IOException e1) {
_clientsMap.clear();
_clientsSocketMap.clear();
e1.printStackTrace();
}
}
}
}
}