您的位置:首页 > 其它

网页聊天service

2015-12-19 18:16 176 查看
package pers.zkr.chat.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Properties;

public class ChatService {

//使用单例模式来设计ChatService
private static ChatService cs;

//使用Properties对象保存系统的所有用户
private Properties userList;

//使用LinkedList对象保存聊天信息
private LinkedList<String> chatMsg;

//机器私有
private ChatService(){

}

public static ChatService instance(){

if(cs==null){

cs= new  ChatService();

}
return cs;
}

public boolean validLogin(String user,String pass) throws IOException{

String loadPass = loadUser().getProperty(user);

//登录成功!
if(loadPass != null && loadPass.equals(pass)){

return true;
}
return true;
}

//新注册用户
public boolean addUser(String name , String pass) throws Exception{

if(userList == null){

userList = loadUser();

}

if(userList.containsKey(name)){

throw new Exception("用户名已经存在,请重新选择用户名");

}
userList.setProperty(name , pass);

saveUserList();

return true;

}

// 获取系统中所有聊天信息
public String getMsg(){

//如果chatMsg对象为null,表明不曾开始聊天
if(chatMsg == null){

chatMsg=new LinkedList<String>();

return "";
}
StringBuilder result = new StringBuilder();
//将chatMsg中所有聊天信息拼接起来
for(String line : chatMsg){

result.append(line + "\n");
}

return result.toString();
}

//用户发言,添加聊天信息
public void addMsg(String user , String  msg){

if(chatMsg == null){

chatMsg = new LinkedList<String>();

}
//最多保存40条聊天信息,当超过40条之后,将前面聊天信息删除
if(chatMsg.size() > 40){

chatMsg.removeFirst();

}
//添加新的聊天信息
chatMsg.add(user + "说:" + msg);
}

//************************下面是私有的系统的工具类
private boolean saveUserList() throws  IOException {
// TODO Auto-generated method stub
if(userList == null){

return false;
}

userList.store(new FileOutputStream("userFile.properties"),
"User info list");
return true;
}

private  Properties loadUser() throws IOException {
// TODO Auto-generated method stub
if(userList == null){

//加载userFile.properties文件
File f=new File("userFile.properties");

if(!f.exists()){

f.createNewFile();//不存在新建

}
String path= f.getAbsolutePath();

System.out.println(path);

userList =new Properties();

userList.load(new FileInputStream(f));
}

return userList;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: