服务器主要功能
- 服务器启动
- 服务器关闭
- 消息转发
- 客户端请求响应
- 接收客户端
- 观察者模式
1.0启动服务器
建立Socket,开启侦听线程。
public void openServer() {
try {
serverSocket = new ServerSocket(INetConfigure.port);
publishMessage("服务器启动成功!");
publishMessage("等待客户端连接......!");
goon = true;
new Thread(this).start();
} catch (IOException e) {
goon = false;
}
}
2 侦听线程
每侦听到客户端连接,构建一个会话层,将其加入临时客户端,并进行客户端验证。
@Override
public void run() {
while(goon) {
try {
Socket client_socket = serverSocket.accept();
ServerConversation serverConversation = new ServerConversation(client_socket,this);
int MAX_COUNT = 10;
if (tempClientPool.getClientCount() + clientPool.getClientCount() >= MAX_COUNT) {
serverConversation.outOfRoom();
continue;
}
tempClientPool.addClient(serverConversation);
serverConversation.whoAreYou();
} catch (IOException e) {
close();
}
}
close();
}
3. 服务器关闭
private void close() {
goon = false;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ignored) {
} finally {
serverSocket = null;
}
}
}
3.1宕机
public void shutDown() {
if (tempClientPool.getClientCount() + clientPool.getClientCount() > 0) {
publishMessage("客户端尚未全部关闭!");
return;
}
close();
}
3.2 强制下线
public void forceDown() {
if (!tempClientPool.isEmpty()) {
ServerConversation serverConversation = tempClientPool.popClient();
serverConversation.forceDown();
}
for (ServerConversation serverConversation : clientPool.clientList()) {
serverConversation.forceDown();
clientPool.removeClient(serverConversation.getId());
}
}
4.消息转发
public void talkToOne(String targetId,String message) {
clientPool.getClient(targetId).toOne(message);
}
public void talkToOthers(String sourceId,String message) {
List<ServerConversation> clients = clientPool.clientsExceptOne(sourceId);
for (ServerConversation client : clients) {
client.talkToOthers(message);
}
}
5. 请求响应
这里提供一个接口,供会话层调用。具体处理方法,需要通过分发器发布到响应的类方法中。
private IActionProcess actionProcess;
public IActionProcess getActionProcess() {
return actionProcess;
}
public void setActionProcess(IActionProcess actionProcess) {
this.actionProcess = actionProcess;
}
6.观察者模式
监听服务器状态
private final List<IListener> listeners = new ArrayList<>();
@Override
public void addListener(IListener listener) {
if (listeners.contains(listener)) {
return;
}
listeners.add(listener);
}
@Override
public void removeListener(IListener listener) {
listeners.remove(listener);
}
@Override
public void publishMessage(String message) {
for (IListener listener : listeners) {
listener.processMessage(message);
}
}