package pachalen.socketconnection.server;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import pachalen.javadebug.JavaDebugTool;
import pachalen.socketconnection.MessageType;
import pachalen.socketconnection.SocketAct;
import pachalen.socketconnection.SocketMessage;
public class ServerRunState implements ServerState{
private JavaDebugTool D;
SocketServer serv = SocketServer.INST;
public ServerRunState(){
try {
D = new JavaDebugTool("ServerRunState");
} catch (Exception e) {}
}
@Override
public void setUp() {
// TODO Auto-generated method stub
D.Debug("������ �������϶��� ������ �� �����ϴ�.");
}
@Override
public void setDown() {
// TODO Auto-generated method stub
try {
serv.serverSocket.close();
serv.currentState = serv.serverWaitState;
} catch (IOException e) {
// TODO Auto-generated catch block
D.Error("�����߿� �̻� ��");
e.printStackTrace();
}
}
@Override
public void addAct(MessageType msg, SocketAct act) {
D.Debug("������ �������϶��� �߰��� �� �����ϴ�.");
}
@Override
public void removeAct(MessageType msg) {
D.Debug("������ �������϶��� ������ �� �����ϴ�.");
}
@Override
public synchronized String login(SocketMessage message, ObjectOutputStream writer) {
try{
if(serv.clientOutputStreams.containsKey(message.getSender())){
writer.writeObject(new SocketMessage(SocketMessage.MsgType.LOGIN_FAILURE,"Server","�����̸� �ߺ�",null));
}
else{
serv.clientOutputStreams.put(message.getSender(), writer);
D.Debug("Username : " + message.getSender() + " �� �α��εǾ����ϴ�.");
sendUserList();
return message.getSender();
}
}catch(Exception e){
D.Error("�α��� �߿� ������");
e.printStackTrace();
}
return null;
}
@Override
public synchronized void logout(SocketMessage message) {
serv.clientOutputStreams.remove(message.getSender());
D.Debug("Username : " + message.getSender() + " �� �αƿ��Ǿ����ϴ�.");
sendUserList();
}
@Override
public synchronized void act(SocketMessage message, ObjectOutputStream writer) {
if(serv.MessageTypes.containsKey(message.getDetailMsgType())){
serv.MessageTypes.get(message.getDetailMsgType()).act(message);
}
else{
D.Error("���� Ÿ�Կ� �����ϴ� �ൿ�� �������� �ʽ��ϴ�.");
}
}
public void sendUserList(){
String userlist = "";
Set<String> s = serv.clientOutputStreams.keySet();
Iterator<String> it = s.iterator();
while(it.hasNext()){
String user = it.next();
userlist += user;
if(it.hasNext()) userlist += "/";
}
it = s.iterator();
String user;
SocketMessage message = new SocketMessage(SocketMessage.MsgType.LOGIN_LIST,userlist,null, null);
while(it.hasNext()){
user = it.next();
try{
ObjectOutputStream writer = serv.clientOutputStreams.get(user);
message.setReceiver(user);
writer.writeObject(message);
writer.flush();
}
catch(Exception e){
D.Error(user + "Ŭ���̾�Ʈ�� ������ ������ �� ������ - " + e);
e.printStackTrace();
return;
}
}
D.Debug("����� ��� Ŭ���̾�Ʈ�� ����Ʈ ���� - " + message);
}
}