📄 sessionhandler.java
字号:
/*
* Created on May 30, 2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.GTADS.server;
import java.net.*;
import java.io.*;
import org.GTADS.server.PeriodicClientPing.UserPing;
import org.GTADS.usermanager.*;
import org.GTADS.messenger.*;
import org.GTADS.protocol.*;
import org.GTADS.debug.*;
import org.GTADS.helper.*;
import java.util.*;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SessionHandler{
Socket clientInstance;
DSChatServer thisServer;
public SessionHandler(Socket clientInstance) throws IOException{
this.clientInstance = clientInstance;
try {
init();
} catch (SocketException se) {
ServerLogger.sendConsoleDebugMessage("Software caused connection abort of "
+ clientInstance.getRemoteSocketAddress(), this.getClass(), 3);
}
}
private void init() throws IOException, SocketException{
// Login Sequence
String userName;
String dataIn;
User currentUser;
int loginSuccess;
MetaData loginHeader = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.LOGIN_SESSION);
loginSuccess = AuthenticationManager.requestAuthentication(clientInstance, thisServer);
if (loginSuccess == AuthenticationManager.LOGIN_SUCCESS){
userName = new String((String)ServerCacheHandler.socketUserCache.get(clientInstance));
currentUser = new User(userName);
MessageAdapter.sendData(currentUser,clientInstance, loginHeader, ProtocolHandler.LOGIN_SUCCESS);
ServerLogger.sendConsoleDebugMessage("User " + userName + " has logged in on " +
clientInstance.getRemoteSocketAddress(), this.getClass(), 4);
}
else if (loginSuccess == AuthenticationManager.MAXED_OUT){
MessageAdapter.sendData(null, clientInstance, loginHeader, ProtocolHandler.MAXED_USERS);
ServerLogger.sendConsoleDebugMessage("Users maxed out: " + clientInstance.getRemoteSocketAddress().toString()
+ " unable to connect "
, this.getClass(), 4);
return;
}
// TODO: Handle new users
else if (loginSuccess == AuthenticationManager.NEW_USER_SUCCESS){
MetaData newUserSuccess = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.LOGIN_SESSION);
MessageAdapter.sendData(null, clientInstance, newUserSuccess, ProtocolHandler.LOGIN_SUCCESS);
ServerLogger.sendConsoleDebugMessage("New user created", this.getClass(), 5);
return;
}
else if (loginSuccess == AuthenticationManager.NEW_USER_DISABLED){
MetaData newUserFail = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.NEW_USER_ACCT);
MessageAdapter.sendData(null, clientInstance, newUserFail, "DISABLED");
return;
}
else if (loginSuccess == AuthenticationManager.NEW_USER_FAIL){
MetaData newUserFail = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.NEW_USER_ACCT);
MessageAdapter.sendData(null, clientInstance, newUserFail, ProtocolHandler.LOGIN_FAIL);
return;
}
else if (loginSuccess == AuthenticationManager.USER_BANNED){
MessageAdapter.sendData(null, clientInstance, loginHeader, MetaData.USER_BANNED);
ServerLogger.sendConsoleDebugMessage("User is banned from server!", this.getClass(), 4);
return;
}
else {
MessageAdapter.sendData(null, clientInstance, loginHeader, ProtocolHandler.LOGIN_FAIL);
ServerLogger.sendConsoleDebugMessage("Failed Login Attempt for " + clientInstance.getRemoteSocketAddress().toString()
, this.getClass(), 4);
return;
}
// Check if proxy port is open not compatible with Beta Release 1.0
if (!checkProxyPortOpen(clientInstance)){
MetaData proxyFailed = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.PROXY_CHECK);
MessageAdapter.sendData(null, clientInstance,proxyFailed,MetaData.PROXY_FAIL);
ServerLogger.sendConsoleDebugMessage("User's Proxy port closed or old client version", this.getClass(), 4);
ServerCacheHandler.userProxyPortState.put(userName,new Boolean(false));
}
else {
ServerCacheHandler.userProxyPortState.put(userName,new Boolean(true));
}
Date d = new Date(); // Set uptime for user
Long uptime = new Long(d.getTime());
ServerCacheHandler.userUptimeCache.put(userName, uptime);
FriendsListManager.getInstance().announceFriendsSignOn(userName);
MetaData motdHeader = new MetaData(MetaData.FROM_SERVER, MetaData.CHATROOM, MetaData.NO_SESSION_NAME);
displayMotd(motdHeader,currentUser);
DataInputStream din = new DataInputStream(clientInstance.getInputStream());
int i = 0;
try {
do {
dataIn = din.readUTF();
i++;
if (i >= 100){
i = 0;
checkUserLimit((String)ServerCacheHandler.socketUserCache.get(clientInstance));
}
if (dataIn != null) {
handleDataInput(dataIn, currentUser);
}
} while (dataIn != null);
} catch (IOException ioe) {
if (currentUser.getChatroom() == null || currentUser.getChatroom().isEmpty())
throw ioe;
else {
//for (int i = 0; i<currentUser.getChatroom().size(); i++){
// ((Chatroom)ServerCacheHandler.chatroomNameCache.
// get(currentUser.getChatroom().get(i))).removeUserFromChatroom(currentUser.getUsername());
// Send message to chatroom notifying everyone
// That currentUser is off the list
// TODO figure out where to clean up empty chatrooms
// Perhaps PeriodicStatusChecker or another timer based
// server thread
//}
}
}
catch (NullPointerException npe){
npe.printStackTrace();
throw new IOException();
}
}
private boolean checkProxyPortOpen(Socket clientSocket) throws IOException {
boolean isOpenProxy = false;
String incomingString = new String();
String proxyPort = new String();
MetaData requestProxyCheckHeader = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.PROXY_CHECK);
MessageAdapter.sendData(null,clientSocket,requestProxyCheckHeader,"NULL");
clientSocket.setSoTimeout(10000);
// Wait 10 seconds
try {
DataInputStream din = new DataInputStream(clientSocket.getInputStream());
incomingString = din.readLine();
if (incomingString != null) {
if (incomingString.split(",").length >= 4){
proxyPort = incomingString.split(",")[3];
Integer proxyPortInt = Integer.valueOf(proxyPort);
byte[] b = new byte[1];
b[0] = 1;
DatagramSocket checkSocket = new DatagramSocket();
DatagramPacket checkPacket = new DatagramPacket(b,1,clientSocket.getInetAddress(),
proxyPortInt.intValue());
checkSocket.send(checkPacket);
incomingString = din.readLine();
if (incomingString.split(",").length >= 4){
if (incomingString.split(",")[3].equalsIgnoreCase(MetaData.PROXY_SUCCESS)){
isOpenProxy = true;
}
}
checkSocket.close();
clientSocket.setSoTimeout(0);
}
}
} catch (InterruptedIOException ioe){
clientSocket.setSoTimeout(0);
} catch (NumberFormatException nfe){
clientSocket.setSoTimeout(0);
}
return isOpenProxy;
}
private static boolean checkProxyPortOpen(Socket clientSocket, String proxyPort) throws IOException {
boolean isOpenProxy = false;
String incomingString = new String();
MetaData requestProxyCheckHeader = new MetaData(MetaData.FROM_SERVER, MetaData.GENERIC, MetaData.PROXY_CHECK);
MessageAdapter.sendData(null,clientSocket,requestProxyCheckHeader,"NULL");
// Wait 10 seconds
try {
if (incomingString != null) {
Integer proxyPortInt = Integer.valueOf(proxyPort);
byte[] b = new byte[1];
b[0] = 1;
DatagramSocket checkSocket = new DatagramSocket();
DatagramPacket checkPacket = new DatagramPacket(b,1,clientSocket.getInetAddress(),
proxyPortInt.intValue());
checkSocket.send(checkPacket);
checkSocket.close();
}
} catch (InterruptedIOException ioe){
clientSocket.setSoTimeout(0);
} catch (NumberFormatException nfe){
clientSocket.setSoTimeout(0);
}
return isOpenProxy;
}
private void displayMotd(MetaData md, User u) throws IOException{
String motd[];;
int count, lines;
if (ServerConfig.getInstance().getMotd() != null) {
lines = ServerConfig.getInstance().getMotd().split("\r\n").length;
motd = new String[lines];
motd = ServerConfig.getInstance().getMotd().split("\r\n");
}
else
return;
for (count = 0; count < motd.length; count++)
MessageAdapter.sendData(u.getUsername(),clientInstance,md, motd[count]);
}
public void handleDataInput(String dataIn, User currentUser) throws IOException {
dataIn = Helper.clipCarriageReturn(dataIn);
String recipient = ProtocolHandler.getDataFromMessage(dataIn,ProtocolHandler.RECIPIENT);
String context = ProtocolHandler.getDataFromMessage(dataIn,ProtocolHandler.CONTEXT);
String session = ProtocolHandler.getDataFromMessage(dataIn,ProtocolHandler.SESSION);
String message = ProtocolHandler.getDataFromMessage(dataIn,ProtocolHandler.MESSAGE);
// TODO: May have to modify this for Clustering between servers
// Probably won't happen for a while
if (recipient != null && ServerCacheHandler.userSocketCache.containsKey(recipient)
&& recipient.equals(currentUser.getUsername())){
if (context != null && context.equalsIgnoreCase(MetaData.GENERIC + "")){
// None chat general requests
if (session != null && session.equalsIgnoreCase(MetaData.JOIN_CHATROOM)){
// Request to Join a Chatroom
if (message != null){
if (Chatroom.isCorrectChatroomName(message)){
// Check if Maximum Chatrooms are reached on Server
if (ServerCacheHandler.chatroomNameCache.containsKey(message)){
// If the room exists already add the user
// but don't create a new room in the Server Cache
if (((Chatroom)ServerCacheHandler.chatroomNameCache.get(message)).hasUser(currentUser.getUsername())){
// If user already exists in the chatroom do nothing.
return;
}
else {
// Check if chatroom is not full
if (ServerConfig.getInstance().getMaxInChatrooms() > 0){
int userCount = ((Chatroom)ServerCacheHandler.chatroomNameCache.get(message)).getListOfUsers().size();
if (userCount >= ServerConfig.getInstance().getMaxInChatrooms() &&
!currentUser.getUsername().equalsIgnoreCase(ServerConfig.getInstance().getAdminAccount())){
ErrorManager.sendErrorToClient(clientInstance, ErrorManager.CHATROOM_FULL);
return;
}
}
((Chatroom)ServerCacheHandler.chatroomNameCache.get(message)).addUserToChatroom(currentUser.getUsername());
Vector v = new Vector();
if (ServerCacheHandler.userChatroomCache.containsKey(currentUser.getUsername())){
v = (Vector)ServerCacheHandler.userChatroomCache.get(currentUser.getUsername());
}
else {
v = new Vector();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -