6.面向对象程序设计(3)
com.langsin.LZChat.server2项目内的代码
jdbc包
1 package jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.util.ArrayList; 8 9 import model.TeamInfo; 10 import model.UserInfo; 11 /** 12 * 建表 ddl dml select 13 * 14 * 1.获取连接 15 * 2.获取Statement 16 * 3.执行Statement 17 * 4.如果是select语法,那么有ResultSet接受结果集 18 * 5.关闭st和connection 19 * 20 * 21 * */ 22 public class jdbcUtil { 23 24 private static String username = "lz"; 25 private static String pwd = "123"; 26 private static String url = "jdbc:oracle:thin:@localhost:1521:orcl"; 27 private static String driver = "oracle.jdbc.driver.OracleDriver"; 28 private static Connection conn = null; 29 30 public static Connection getConnection() { 31 try { 32 Class.forName(driver); 33 conn = DriverManager.getConnection(url, username, pwd); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 38 return conn; 39 } 40 public static void main(String[] args) { 41 new jdbcUtil().getConnection(); 42 } 43 // 注册qq号 44 public void Reg(int qq, String pwd, String nickname, byte icon, String sex) { 45 conn = jdbcUtil.getConnection(); 46 String sql = "insert into qqUser values(?,?,?,?,?,'')"; 47 PreparedStatement ps = null; 48 try { 49 ps = conn.prepareStatement(sql); 50 ps.setInt(1, qq); 51 ps.setString(2, pwd); 52 ps.setString(3, nickname); 53 ps.setByte(4, icon); 54 ps.setString(5, sex); 55 ps.execute(); 56 conn.commit(); 57 conn.close(); 58 } catch (Exception e) { 59 e.printStackTrace(); 60 } 61 } 62 63 // 验证登陆 64 public UserInfo checkLogin(int qq, String pwd) { 65 conn = jdbcUtil.getConnection(); 66 String sql = "select * from qqUser where qq=?"; 67 PreparedStatement ps = null; 68 ResultSet rs = null; 69 UserInfo user = null; 70 try { 71 ps = conn.prepareStatement(sql); 72 ps.setInt(1, qq); 73 rs = ps.executeQuery(); 74 while (rs.next()) { 75 if(!pwd.equals(rs.getString(2))){ 76 return null; 77 } 78 user = new UserInfo(rs.getInt(1), rs.getString(3), 79 rs.getString(5)); 80 user.setIcon(rs.getByte(4)); 81 TeamInfo team = new TeamInfo(""); 82 String friendstr = rs.getString(6); 83 System.out.println("friendstr:"+friendstr); 84 if (friendstr!=null) { 85 String[] friends = rs.getString(6).split(","); 86 87 for (int i = 0; i < friends.length; i++) { 88 UserInfo userinfo = new UserInfo( 89 Integer.valueOf(friends[i])); 90 team.addFriend(userinfo); 91 } 92 } 93 ArrayList<TeamInfo> teams = new ArrayList<TeamInfo>(); 94 teams.add(team); 95 user.setTeams(teams); 96 } 97 conn.commit(); 98 conn.close(); 99 } catch (Exception e) { 100 e.printStackTrace(); 101 } 102 return user; 103 } 104 105 // 根据qq 得到用户信息 106 public UserInfo getUser(int qq) { 107 conn = jdbcUtil.getConnection(); 108 String sql = "select * from qqUser where qq=?"; 109 PreparedStatement ps = null; 110 ResultSet rs = null; 111 UserInfo user = null; 112 try { 113 ps = conn.prepareStatement(sql); 114 ps.setInt(1, qq); 115 rs = ps.executeQuery(); 116 while (rs.next()) { 117 user = new UserInfo(qq, rs.getString(3), rs.getString(5)); 118 user.setIcon(rs.getByte(4)); 119 TeamInfo team = new TeamInfo(""); 120 if (rs.getString(6) != null) { 121 String[] friends = rs.getString(6).split(","); 122 123 for (int i = 0; i < friends.length; i++) { 124 UserInfo userinfo = new UserInfo( 125 Integer.valueOf(friends[i])); 126 team.addFriend(userinfo); 127 } 128 } 129 ArrayList<TeamInfo> teams = new ArrayList<TeamInfo>(); 130 teams.add(team); 131 user.setTeams(teams); 132 } 133 conn.commit(); 134 conn.close(); 135 } catch (Exception e) { 136 e.printStackTrace(); 137 } 138 return user; 139 } 140 141 // 添加好友 142 public void addFriend(int qq, int friend) { 143 conn = jdbcUtil.getConnection(); 144 String sql = "select friend from qqUser where qq=?"; 145 PreparedStatement ps = null; 146 ResultSet rs = null; 147 String friends = ""; 148 try { 149 ps = conn.prepareStatement(sql); 150 ps.setInt(1, qq); 151 rs = ps.executeQuery(); 152 while (rs.next()) { 153 154 friends = rs.getString(1); 155 if(friends==null){ 156 friends = friend + ","; 157 }else 158 friends = friends+ friend+","; 159 160 } 161 162 // 存入数据库 163 sql = "update qqUser set friend=? where qq=?"; 164 ps = conn.prepareStatement(sql); 165 ps.setString(1, friends); 166 ps.setInt(2, qq); 167 ps.execute(); 168 conn.commit(); 169 conn.close(); 170 } catch (Exception e) { 171 e.printStackTrace(); 172 } 173 } 174 175 // 获得最大号 176 public int GetMaxNum() { 177 int maxNum = 1000; 178 conn = getConnection(); 179 PreparedStatement ps = null; 180 ResultSet rs = null; 181 String sql = "select max(qq) from qqUser"; 182 try { 183 ps = conn.prepareStatement(sql); 184 rs = ps.executeQuery(); 185 while (rs.next()) { 186 if (rs.getInt(1) > 1000) 187 maxNum = rs.getInt(1); 188 } 189 } catch (Exception e) { 190 e.printStackTrace(); 191 } 192 maxNum++; 193 return maxNum; 194 } 195 196 // 调试数据库 197 // public static void main(String[] args) { 198 // jdbcUtil jdbc = new jdbcUtil(); 199 // jdbc.Reg(123, "456", "sad", (byte)1, "男"); 200 // jdbc.checkLogin(123, "456"); 201 // } 202 }
model包
1 package model; 2 3 import java.io.Serializable; 4 import java.util.ArrayList; 5 6 /*** 7 * 用户类 8 * @author Administrator 9 * 10 */ 11 @SuppressWarnings("serial") 12 public class UserInfo implements Serializable{ 13 14 private int qq; //qq号码 15 private String pwd; //密码 16 private String nickname; //用户昵称 17 private String sex; //用户性别 18 private byte icon; //头像 19 20 private byte onLine = 1; //用户是否在线 默认为1 即不在线 21 22 private ArrayList<TeamInfo> teams = new ArrayList<TeamInfo>(); //好友列表 23 24 public UserInfo(int qq){ 25 this.qq = qq; 26 // init(); 27 } 28 29 public UserInfo(int qq,String nickname,String sex){ 30 this.qq = qq; 31 this.nickname = nickname; 32 this.sex = sex; 33 // init(); 34 } 35 36 //初始化用户 37 // public void init(){ 38 // TeamInfo team1,team2,team3; 39 // team1= new TeamInfo(0, "我的好友", this.qq); 40 // team2= new TeamInfo(1, "陌生人", this.qq); 41 // team3= new TeamInfo(2, "黑名单", this.qq); 42 // this.teams.add(team1); 43 // this.teams.add(team2); 44 // this.teams.add(team3); 45 // } 46 47 public void addTeam(TeamInfo team){ 48 this.teams.add(team); 49 } 50 51 52 //get set 方法 53 54 55 public int getQq() { 56 return qq; 57 } 58 59 public byte getIcon() { 60 return icon; 61 } 62 63 public void setIcon(byte icon) { 64 this.icon = icon; 65 } 66 67 public byte getOnLine() { 68 return onLine; 69 } 70 71 public void setOnLine(byte onLine) { 72 this.onLine = onLine; 73 } 74 75 public String getSex() { 76 return sex; 77 } 78 79 public void setSex(String sex) { 80 this.sex = sex; 81 } 82 83 public void setQq(int qq) { 84 this.qq = qq; 85 } 86 87 public String getPwd() { 88 return pwd; 89 } 90 91 public void setPwd(String pwd) { 92 this.pwd = pwd; 93 } 94 95 public String getNickname() { 96 return nickname; 97 } 98 99 public void setNickname(String nickname) { 100 this.nickname = nickname; 101 } 102 103 public ArrayList<TeamInfo> getTeams() { 104 return teams; 105 } 106 107 public void setTeams(ArrayList<TeamInfo> teams) { 108 this.teams = teams; 109 } 110 111 @Override 112 public String toString() { 113 return "UserInfo [qq=" + qq + ", nickname=" + nickname + ", sex=" + sex 114 + ", icon=" + icon + "]"; 115 } 116 117 118 }
1 package model; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.ObjectInputStream; 7 import java.io.ObjectOutputStream; 8 import java.util.Collections; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 import tools.LogTools; 13 14 /*** 15 * 数据存储 16 * @author Administrator 17 * 18 */ 19 @SuppressWarnings({ "unchecked", "rawtypes" }) 20 public class UserDao { 21 22 private static int maxQQNumber = 1000; 23 private static final String dbFileName = "qq.dat"; 24 private static Map<Integer, UserInfo> userDB = new HashMap<Integer,UserInfo>(); 25 26 static{ 27 try { 28 File file = new File(dbFileName); 29 if(file.exists()&&!file.isDirectory()){ 30 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); 31 userDB = (Map)ois.readObject(); 32 LogTools.INFO(UserDao.class, "从数据文件读取数据成功!"); 33 }else{ 34 LogTools.ERROR(UserDao.class, "不存在数据文件,创建空表"); 35 } 36 37 } catch (Exception e) { 38 // TODO: handle exception 39 } 40 } 41 42 //用户登录 43 public static UserInfo checkLogin(int qq,String pwd){ 44 UserInfo user = userDB.get(qq); 45 if(null!=user && pwd.equals(user.getPwd())){ 46 LogTools.INFO(UserDao.class, "登录成功!"); 47 return user; 48 } 49 LogTools.ERROR(UserDao.class, "登录失败!"); 50 return null; 51 } 52 53 //注册用户 54 public static int regUser(String pwd,String nickname,String sex){ 55 if(userDB.size()>0){ 56 maxQQNumber = Collections.max(userDB.keySet()); 57 } 58 maxQQNumber++; 59 UserInfo user = new UserInfo(maxQQNumber); 60 user.setPwd(pwd); 61 user.setNickname(nickname); 62 user.setSex(sex); 63 userDB.put(maxQQNumber, user); 64 saveDB(); 65 return maxQQNumber; 66 } 67 68 //将内存中的数据保存到文件中 69 private static void saveDB(){ 70 try { 71 ObjectOutputStream ois = new ObjectOutputStream(new FileOutputStream(dbFileName)); 72 ois.writeObject(userDB); 73 ois.close(); 74 LogTools.INFO(UserDao.class, "刷新数据文件成功!"); 75 } catch (Exception e) { 76 LogTools.ERROR(UserDao.class, "刷新数据文件失败:"+e); 77 } 78 } 79 80 /** 81 * 根据qq号码 得到用户的信息 82 * @param qq qq号码 83 * @return 用户的信息 84 */ 85 public static UserInfo getUserInfo(int qq){ 86 return userDB.get(qq); 87 } 88 89 /** 90 * 添加好友的数据库操作 91 * @param qq1 92 * @param qq2 相互添加好友的号码 93 * @param groupName1 94 * @param groupName2 分别加入的群组 95 */ 96 public static void addFriend(int qq1,int qq2,String groupName1,String groupName2){ 97 UserInfo user1 = getUserInfo(qq1); 98 UserInfo user2 = getUserInfo(qq2); 99 //暂时默认添加到好友队列 100 user1.getTeams().get(0).addFriend(user2); 101 user2.getTeams().get(0).addFriend(user1); 102 //保存 103 saveDB(); 104 } 105 }
1 package model; 2 3 import java.io.ByteArrayInputStream; 4 import java.io.DataInputStream; 5 import java.io.IOException; 6 import java.util.ArrayList; 7 8 import msg.MsgAddFriend; 9 import msg.MsgAddFriendResp; 10 import msg.MsgAddYou; 11 import msg.MsgAddYouResp; 12 import msg.MsgChatFile; 13 import msg.MsgChatText; 14 import msg.MsgFindResp; 15 import msg.MsgHead; 16 import msg.MsgLogin; 17 import msg.MsgLoginResp; 18 import msg.MsgPerData; 19 import msg.MsgReg; 20 import msg.MsgRegResp; 21 import msg.MsgTeamList; 22 import msg.MsgType; 23 import tools.LogTools; 24 25 /*** 26 * 解包消息 27 * 28 * @author Administrator 29 * 30 */ 31 public class ToolsParseMsg { 32 33 public static MsgHead parseMsg(byte[] data) throws IOException { 34 int totalLen = data.length + 4; // 算出消息总长 35 ByteArrayInputStream bis = new ByteArrayInputStream(data); 36 DataInputStream dis = new DataInputStream(bis); 37 byte msgType = dis.readByte(); 38 int src = dis.readInt(); 39 int dest = dis.readInt(); 40 MsgHead msgHead = new MsgHead(); 41 msgHead.setTotalLen(totalLen); 42 msgHead.setType(msgType); 43 msgHead.setSrc(src); 44 msgHead.setDest(dest); 45 //根据类型进行判断 46 switch (msgType) { 47 //注册 48 case MsgType.command_reg: 49 MsgReg mr = new MsgReg(); 50 copyHead(msgHead, mr); 51 String nickname = readString(dis, 10); 52 mr.setNickname(nickname); 53 String pwd = readString(dis, 10); 54 mr.setPwd(pwd); 55 String sex = readString(dis, 10); 56 mr.setSex(sex); 57 byte icon = dis.readByte(); 58 mr.setIcon(icon); 59 return mr; 60 //注册应答 61 case MsgType.command_reg_resp: 62 MsgRegResp mrr = new MsgRegResp(); 63 copyHead(msgHead, mrr); 64 mrr.setState(dis.readByte()); 65 return mrr; 66 //登陆 67 case MsgType.command_login: 68 MsgLogin ml = new MsgLogin(); 69 copyHead(msgHead, ml); 70 ml.setPwd(readString(dis, 10)); 71 return ml; 72 //登陆应答 73 case MsgType.command_login_resp: 74 MsgLoginResp mlr = new MsgLoginResp(); 75 copyHead(msgHead, mlr); 76 mlr.setState(dis.readByte()); 77 return mlr; 78 //好友列表 79 case MsgType.command_teamList: 80 MsgTeamList mtl =new MsgTeamList(); 81 copyHead(msgHead, mtl); 82 int listCount = dis.readInt(); //得到分组个数 83 ArrayList<TeamInfo> teamList = new ArrayList<TeamInfo>(); 84 for (int i = 0; i < listCount; i++) { 85 String groupName = readString(dis, 10); //得到某一分组名字 86 TeamInfo teamInfo = new TeamInfo(groupName); 87 byte usersCount = dis.readByte(); //得到某一分组的成员个数 88 for (int j = 0; j < usersCount; j++) { 89 int qq = dis.readInt(); //得到qq号码 90 String nickname2 = readString(dis, 10); //得到昵称 91 String sex2 = readString(dis, 10); //得到性别 92 byte teamList_icon = dis.readByte(); //得到头像 93 94 byte onLine = dis.readByte(); //得到是否在线 95 UserInfo userInfo = new UserInfo(qq, nickname2, sex2); 96 userInfo.setOnLine(onLine); 97 userInfo.setIcon(teamList_icon); 98 teamInfo.addFriend(userInfo); 99 } 100 teamList.add(teamInfo); 101 } 102 mtl.setTeamList(teamList); 103 return mtl; 104 //在线qq列表 返回 105 case MsgType.command_find_resp: 106 MsgFindResp mfr = new MsgFindResp(); 107 copyHead(msgHead, mfr); 108 int count = dis.readInt(); 109 for (int i = 0; i < count; i++) { 110 int qq = dis.readInt(); 111 String nickName = readString(dis, 10); 112 String mfr_sex = readString(dis, 10); 113 byte find_resp_icon = dis.readByte(); 114 UserInfo userInfo = new UserInfo(qq, nickName, mfr_sex); 115 userInfo.setIcon(find_resp_icon); 116 mfr.addQq(userInfo); 117 } 118 return mfr; 119 //添加好友 请求 120 case MsgType.command_addFriend: 121 MsgAddFriend maf = new MsgAddFriend(); 122 copyHead(msgHead, maf); 123 maf.setFriendQq(dis.readInt()); 124 String note = readString(dis, 30); //!!!!!!30字节长度!!!!!! 125 maf.setNote(note); 126 return maf; 127 //添加好友 回复 128 case MsgType.command_addFriend_Resp: 129 MsgAddFriendResp mafr = new MsgAddFriendResp(); 130 copyHead(msgHead, mafr); 131 mafr.setState(dis.readByte()); 132 mafr.setQq(dis.readInt()); 133 String nickName = readString(dis, 10); 134 mafr.setNickName(nickName); 135 String addFriend_Resp_sex = readString(dis, 10); //性别 136 mafr.setSex(addFriend_Resp_sex); 137 mafr.setIcon(dis.readByte()); 138 return mafr; 139 //有人添加你为好友 140 case MsgType.command_addYou: 141 MsgAddYou may = new MsgAddYou(); 142 copyHead(msgHead, may); 143 String addYou_nickname = readString(dis, 10); 144 may.setNickname(addYou_nickname); 145 String addYou_sex = readString(dis, 10); //性别 146 may.setSex(addYou_sex); 147 String addYou_note = readString(dis, 30); //备注 148 may.setNote(addYou_note); 149 return may; 150 //有人添加你为好友 的 回复 151 case MsgType.command_addYouResp: 152 MsgAddYouResp mayr = new MsgAddYouResp(); 153 copyHead(msgHead, mayr); 154 mayr.setState(dis.readByte()); 155 return mayr; 156 //聊天信息 157 case MsgType.command_chatText: 158 MsgChatText mct = new MsgChatText(); 159 copyHead(msgHead, mct); 160 String time = readString(dis, 20); 161 mct.setTime(time); 162 int len = totalLen-4-1-4-4-20; 163 String chat = readString(dis, len); 164 mct.setContent(chat); 165 return mct; 166 //文件传输 167 case MsgType.command_chatFile: 168 MsgChatFile mcf = new MsgChatFile(); 169 copyHead(msgHead, mcf); 170 String chatFile_time = readString(dis, 20); 171 mcf.setTime(chatFile_time); 172 String fileName = readString(dis, 256); 173 mcf.setFileName(fileName); 174 int filelen = totalLen-4-1-4-4-256-20; 175 byte[] fileData = new byte[filelen]; 176 dis.readFully(fileData); 177 mcf.setFileData(fileData); 178 return mcf; 179 case MsgType.command_perdata: 180 MsgPerData mpd = new MsgPerData(); 181 copyHead(msgHead, mpd); 182 String perdata_nickname = readString(dis, 10); 183 mpd.setNickname(perdata_nickname); 184 String perdata_sex = readString(dis, 10); 185 mpd.setSex(perdata_sex); 186 mpd.setIcon(dis.readByte()); 187 return mpd; 188 //返回在线qq号码请求 189 case MsgType.command_find: 190 case MsgType.command_onLine: 191 case MsgType.command_offLine: 192 case MsgType.command_vibration: 193 return msgHead; 194 default: 195 String logMsg = "解包未知消息类型,无法解包:type:" + msgType; 196 LogTools.ERROR(ToolsParseMsg.class, logMsg); //记录日志信息 197 break; 198 } 199 200 return null; 201 202 } 203 204 /** 205 * 复制消息头的数据 206 * @param head 消息头 207 * @param dest 要复制到的对象 208 */ 209 public static void copyHead(MsgHead head,MsgHead dest){ 210 dest.setTotalLen(head.getTotalLen()); 211 dest.setType(head.getType()); 212 dest.setSrc(head.getSrc()); 213 dest.setDest(head.getDest()); 214 } 215 216 /** 217 * 从流中读取len长度的字节 218 * @param dous 流数据 219 * @param len 长度 220 * @throws IOException 221 */ 222 public static String readString(DataInputStream dis,int len) throws IOException{ 223 byte[] data = new byte[len]; 224 dis.readFully(data); 225 return new String(data); 226 } 227 }
package model; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import msg.MsgAddFriend; import msg.MsgAddFriendResp; import msg.MsgAddYou; import msg.MsgAddYouResp; import msg.MsgChatFile; import msg.MsgChatText; import msg.MsgFindResp; import msg.MsgHead; import msg.MsgLogin; import msg.MsgLoginResp; import msg.MsgPerData; import msg.MsgReg; import msg.MsgRegResp; import msg.MsgTeamList; import msg.MsgType; import tools.LogTools; /*** * 打包消息 * @author Administrator * */ public class ToolsCreateMsg { /** * 将消息对象打包成字节数组返回 * @param msg 要打包的消息对象 * @return 返回的字节数组 * @throws IOException */ public static byte[] packMsg(MsgHead msg) throws IOException{ ByteArrayOutputStream bous = new ByteArrayOutputStream(); DataOutputStream dous = new DataOutputStream(bous); writeHead(dous, msg); int msgType = msg.getType(); switch (msgType) { //注册 case MsgType.command_reg: MsgReg mr = (MsgReg)msg; writeString(dous, 10, mr.getNickname()); writeString(dous, 10, mr.getPwd()); writeString(dous, 10, mr.getSex()); dous.writeByte((byte)mr.getIcon()); break; //注册应答 case MsgType.command_reg_resp: MsgRegResp mrr = (MsgRegResp)msg; dous.writeByte(mrr.getState()); break; //登陆 case MsgType.command_login: MsgLogin ml = (MsgLogin) msg; writeString(dous, 10, ml.getPwd()); break; //登陆应答 case MsgType.command_login_resp: MsgLoginResp mlr = (MsgLoginResp) msg; dous.writeByte(mlr.getState()); break; //好友列表 case MsgType.command_teamList: MsgTeamList mtl = (MsgTeamList)msg; ArrayList<TeamInfo> teams = mtl.getTeamList(); int listCount = teams.size(); dous.writeInt(listCount); //写入分组个数 for (TeamInfo teamInfo : teams) { writeString(dous, 10, teamInfo.getName()); //写入分组名字 ArrayList<UserInfo> users = teamInfo.getFriendList(); dous.writeByte(users.size()); //写入一个分组的成员个数 for (UserInfo userInfo : users) { dous.writeInt(userInfo.getQq()); //写入qq号 writeString(dous, 10, userInfo.getNickname()); //写入昵称 writeString(dous, 10, userInfo.getSex()); //写入性别 dous.writeByte(userInfo.getIcon()); //写入头像 dous.writeByte(userInfo.getOnLine()); //写入是否在线 } } break; //返回在线qq号码 case MsgType.command_find_resp: MsgFindResp mfr = (MsgFindResp)msg; ArrayList<UserInfo> users = mfr.getUsers(); dous.writeInt(users.size()); //写入在线qq的数量 for (UserInfo userInfo : users) { dous.writeInt(userInfo.getQq()); //写入qq 昵称 性别 头像 writeString(dous, 10, userInfo.getNickname()); writeString(dous, 10, userInfo.getSex()); dous.writeByte(userInfo.getIcon()); } // for (int i = 0; i < count; i++) { // UserInfo userInfo = users.get(i); // dous.writeInt(userInfo.getQq()); // writeString(dous, 10, userInfo.getNickname()); // writeString(dous, 10, userInfo.getSex()); // } break; //添加好友 case MsgType.command_addFriend: MsgAddFriend maf = (MsgAddFriend) msg; dous.writeInt(maf.getFriendQq()); writeString(dous, 30, maf.getNote()); //!!!!!!30字节长度!!!!!! break; //添加好友应答 case MsgType.command_addFriend_Resp: MsgAddFriendResp magr = (MsgAddFriendResp) msg; dous.writeByte(magr.getState()); //对方是否同意 dous.writeInt(magr.getQq()); //对方qq writeString(dous, 10, magr.getNickName()); //对方昵称 writeString(dous, 10, magr.getSex()); //对方的性别 dous.writeByte(magr.getIcon()); break; //有人添加你为好友 case MsgType.command_addYou: MsgAddYou may = (MsgAddYou) msg; writeString(dous, 10, may.getNickname()); //昵称 writeString(dous, 10, may.getSex()); //性别 writeString(dous, 30, may.getNote()); //备注信息 break; //有人添加你为好友 的 回复 case MsgType.command_addYouResp: MsgAddYouResp mayr = (MsgAddYouResp) msg; dous.writeByte(mayr.getState()); break; //聊天信息 case MsgType.command_chatText: MsgChatText mct = (MsgChatText) msg; writeString(dous, 20, mct.getTime()); dous.write(mct.getContent().getBytes()); break; //文件传输 case MsgType.command_chatFile: MsgChatFile mcf = (MsgChatFile) msg; writeString(dous, 20, mcf.getTime()); writeString(dous, 256, mcf.getFileName()); dous.write(mcf.getFileData()); break; case MsgType.command_perdata: MsgPerData mpd = (MsgPerData) msg; writeString(dous, 10, mpd.getNickname()); writeString(dous, 10, mpd.getSex()); dous.writeByte(mpd.getIcon()); break; //返回在线qq号码请求 case MsgType.command_find: case MsgType.command_onLine: case MsgType.command_offLine: case MsgType.command_vibration: break; default: String logMsg="创建未知消息类型,无法打包:type:"+msgType; LogTools.ERROR(ToolsCreateMsg.class, logMsg); //记录日志 break; } dous.flush(); byte[] data = bous.toByteArray(); return data; } /** * 向流中写入消息头信息 * @param dous 要写入的流对象 * @param msg 消息头对象 * @throws IOException */ public static void writeHead(DataOutputStream dous,MsgHead msg) throws IOException{ dous.writeInt(msg.getTotalLen()); dous.writeByte(msg.getType()); dous.writeInt(msg.getSrc()); dous.writeInt(msg.getDest()); } /** * 向流中写入len长的字符串 * @param dous 要写入的输出流 * @param len 要写入字符串的长度 * @param s 要写入的字符串 * @throws IOException */ public static void writeString(DataOutputStream dous,int len,String s) throws IOException{ byte[] data = s.getBytes(); if(data.length>len) throw new IOException("写入长度为:"+len+",文本过长!"); dous.write(data); while(len>data.length){//如果短,需要补0 dous.writeByte('\0'); //补二进制的0 len--; } } }
1 package model; 2 3 import java.io.Serializable; 4 import java.util.ArrayList; 5 6 /*** 7 * 好友分组 8 * @author Administrator 9 * 10 */ 11 @SuppressWarnings("serial") 12 public class TeamInfo implements Serializable{ 13 14 private int id; //分组id 15 private String name; //分组名字 16 private int ownerUser; //所有者 17 //在此分组内的好友列表 18 private ArrayList<UserInfo> friendList = new ArrayList<UserInfo>(); 19 20 public TeamInfo(int id, String name, int ownerUser) { 21 this.id = id; 22 this.name = name; 23 this.ownerUser = ownerUser; 24 } 25 /** 26 * 为此分组加入一个成员 27 * @param info 28 */ 29 public void addFriend(UserInfo info){ 30 this.friendList.add(info); 31 } 32 33 public TeamInfo(String name) { 34 this.name = name; 35 } 36 37 //get set 方法 38 public int getId() { 39 return id; 40 } 41 42 public void setId(int id) { 43 this.id = id; 44 } 45 46 public String getName() { 47 return name; 48 } 49 50 public void setName(String name) { 51 this.name = name; 52 } 53 54 public int getOwnerUser() { 55 return ownerUser; 56 } 57 58 public void setOwnerUser(int ownerUser) { 59 this.ownerUser = ownerUser; 60 } 61 62 public ArrayList<UserInfo> getFriendList() { 63 return friendList; 64 } 65 66 public void setFriendList(ArrayList<UserInfo> friendList) { 67 this.friendList = friendList; 68 } 69 70 71 }
msg包内容等同于上个项目的msg包
sever包
1 package server; 2 3 import java.io.DataInputStream; 4 import java.io.DataOutputStream; 5 import java.io.IOException; 6 import java.net.Socket; 7 8 import jdbc.jdbcUtil; 9 import model.ToolsCreateMsg; 10 import model.ToolsParseMsg; 11 import model.UserInfo; 12 import msg.MsgHead; 13 import msg.MsgLogin; 14 import msg.MsgLoginResp; 15 import msg.MsgPerData; 16 import msg.MsgReg; 17 import msg.MsgRegResp; 18 import msg.MsgTeamList; 19 import msg.MsgType; 20 import tools.LogTools; 21 22 public class ServerTread extends Thread { 23 24 private jdbcUtil jdbc = new jdbcUtil(); 25 private Socket client; 26 private DataOutputStream dous; //输出流 27 private DataInputStream dis; //输入流 28 private UserInfo ownerUser; 29 private boolean loginOK = false; 30 private boolean ok = false; //注册用户 31 32 public ServerTread(Socket socket){ 33 this.client = socket; 34 } 35 36 @Override 37 public void run() { 38 /** 39 * 读取第一条消息,这个时候称之为:同步消息,等待的消息,必须等消息到达读到才能进行后续代码执行。 40 * 有两种可能:1 登陆 2 注册 41 */ 42 try { 43 loginOK = readFirstMsg(); 44 45 while(loginOK){ 46 MsgHead msg = this.reciveData();// 循环接收消息 47 ServerThreadManage.sendMsgToOther(this.ownerUser,msg);//处理接收到的消息 48 } 49 } catch (IOException e) { 50 // TODO Auto-generated catch block 51 //e.printStackTrace(); 52 LogTools.ERROR(this.getClass(), "连接客户端失败:" + e); 53 } 54 55 if(ok) 56 ServerThreadManage.removeClient(this.ownerUser); 57 } 58 59 /** 60 * 从流中接受数据 并转换为消息对象 61 * @return 消息对象 62 * @throws IOException 63 */ 64 private MsgHead reciveData() throws IOException { 65 int len = dis.readInt(); 66 LogTools.INFO(this.getClass(), "服务器读消息长度:" + len); 67 byte[] data = new byte[len-4]; 68 dis.readFully(data); 69 /** 70 * 现在data数组中有数据了 71 * 接下来就是将data字节数组中的数据解析到对应的消息领域对象中 72 */ 73 MsgHead msg = ToolsParseMsg.parseMsg(data); 74 LogTools.INFO(this.getClass(), "服务器读到消息对象:" + msg); 75 return msg; 76 } 77 78 /** 79 * 读取第一条数据 80 * @return 81 */ 82 private boolean readFirstMsg() { 83 try { 84 this.dous = new DataOutputStream(client.getOutputStream()); 85 this.dis = new DataInputStream(client.getInputStream()); 86 MsgHead msg = reciveData(); 87 if(msg.getType() == MsgType.command_login){ 88 ok = true; 89 MsgLogin ml = (MsgLogin)msg; 90 return checkLogin(ml); 91 } 92 if(msg.getType() == MsgType.command_reg){ 93 MsgReg mr = (MsgReg) msg; 94 // 保存注册,生成qq号,回复应答消息 95 //int qq = UserDao.regUser(mr.getPwd(), mr.getNickname(),mr.getSex(),mr.getIcon()); 96 int qq = jdbc.GetMaxNum(); 97 jdbc.Reg(qq, mr.getPwd(), mr.getNickname(), mr.getIcon(), mr.getSex()); 98 MsgRegResp mrr = new MsgRegResp(); 99 mrr.setTotalLen(4+1+4+4+1); 100 mrr.setType(MsgType.command_reg_resp); 101 mrr.setSrc(MsgType.SERVER_QQ_NUMBER); 102 mrr.setDest(qq); 103 mrr.setState((byte)0); 104 this.sendMsg(mrr); 105 } 106 107 } catch (IOException e) { 108 LogTools.ERROR(this.getClass(), "readFirstMsg失败:" + e); 109 //e.printStackTrace(); 110 } 111 112 return false; 113 } 114 115 116 117 /** 118 * 发送一条消息对象给这个对象所代表的客户端用户 119 * @param msg 要发送的信息 120 * @return 是否发送成功 121 */ 122 public boolean sendMsg(MsgHead msg) { 123 try { 124 byte[] data = ToolsCreateMsg.packMsg(msg); 125 this.dous.write(data); 126 this.dous.flush(); 127 LogTools.INFO(this.getClass(), "服务器发出消息对象:" + msg); 128 return true; 129 } catch (IOException e) { 130 LogTools.ERROR(this.getClass(), "服务器发出消息出错:" + msg); 131 e.printStackTrace(); 132 } 133 return false; 134 } 135 136 137 /** 138 * 检查登陆是否成功 139 * @param ml 登录信息 140 * @return 是否成功 141 */ 142 private boolean checkLogin(MsgLogin ml) { 143 //ownerUser = UserDao.checkLogin(ml.getSrc(),ml.getPwd()); 144 ownerUser = jdbc.checkLogin(ml.getSrc(),ml.getPwd()); 145 if(ownerUser != null){ 146 // 登陆成功1.回应答包,2.将这个处理线程对象加到队列中 147 MsgLoginResp mlr = new MsgLoginResp(); 148 mlr.setTotalLen(4+1+4+4+1); 149 mlr.setType(MsgType.command_login_resp); 150 mlr.setSrc(MsgType.SERVER_QQ_NUMBER); 151 mlr.setDest(ownerUser.getQq()); 152 mlr.setState((byte)0); 153 this.sendMsg(mlr);// 发送应答消息 154 //创建好友信息表 并发送 155 // MsgTeamList mt = new MsgTeamList(); 156 // int len = 4+1+4+4+4; //最后的这个加4: 157 // ArrayList<TeamInfo> teams = ownerUser.getTeams(); 158 // for (TeamInfo teamInfo : teams) { 159 // int count = teamInfo.getFriendList().size(); 160 // len += 10+1; 161 // len += count*(10+4+10); 162 // } 163 // mt.setTotalLen(len); 164 // mt.setSrc(MsgType.SERVER_QQ_NUMBER); 165 // mt.setDest(ownerUser.getQq()); 166 // mt.setType(MsgType.command_teamList); 167 // mt.setTeamList(ownerUser.getTeams()); 168 // this.sendMsg(mt); 169 ServerThreadManage.addClient(ownerUser, this); 170 171 MsgPerData mpd = new MsgPerData(); 172 mpd.setType(MsgType.command_perdata); 173 ServerThreadManage.sendMsgToOther(ownerUser, mpd); 174 175 MsgTeamList mtl = new MsgTeamList(); 176 mtl.setType(MsgType.command_teamList); 177 ServerThreadManage.sendMsgToOther(ownerUser, mtl); 178 return true; 179 } 180 this.disConn();// 登陆失败,直接断开 181 return false; 182 } 183 /** 184 * 断开连结这个处理线程与客户机的连结, 发生异常,或处理线程退出时调用 185 */ 186 public void disConn() { 187 try { 188 loginOK = false; 189 this.client.close(); 190 } catch (IOException e) { 191 e.printStackTrace(); 192 } 193 } 194 }
1 package server; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.Iterator; 6 import java.util.Map; 7 import java.util.Random; 8 import java.util.Set; 9 10 import jdbc.jdbcUtil; 11 import model.TeamInfo; 12 import model.UserInfo; 13 import msg.MsgAddFriend; 14 import msg.MsgAddFriendResp; 15 import msg.MsgAddYou; 16 import msg.MsgAddYouResp; 17 import msg.MsgFindResp; 18 import msg.MsgHead; 19 import msg.MsgPerData; 20 import msg.MsgTeamList; 21 import msg.MsgType; 22 23 /*** 24 * 服务器管理线程的类 25 * 因为需要在其他类中调用 所有方法都为静态方法 26 * @author Administrator 27 * 28 */ 29 public class ServerThreadManage { 30 31 private static jdbcUtil jdbc = new jdbcUtil(); 32 //保存线程的对象列表 33 private static Map<UserInfo,ServerTread> stList = new HashMap<UserInfo, ServerTread>(); 34 //注册码 35 @SuppressWarnings("unused") 36 private static Map<Integer, String> regMsg = new HashMap<Integer, String>(); 37 38 /** 39 * 用户登录后将线程添加到队列中 40 * @param user 用户 41 * @param st 线程 42 */ 43 public static void addClient(UserInfo user,ServerTread st){ 44 stList.put(user, st); 45 setOnOffLineMsg(user, true); 46 } 47 48 /** 49 * 移除列表中的线程 50 * @param user 51 */ 52 public static void removeClient(UserInfo user){ 53 ServerTread ct = stList.remove(user); 54 ct.disConn(); 55 ct = null; 56 setOnOffLineMsg(user, false); 57 } 58 /** 59 * 移除列表中的所有线程 60 * @param user 61 */ 62 public static void removeClients(){ 63 Set<UserInfo> users = stList.keySet(); 64 Iterator<UserInfo> its = users.iterator(); 65 while(its.hasNext()){ 66 ServerTread ct = stList.remove(its.next()); 67 ct.disConn(); 68 ct = null; 69 } 70 } 71 72 /** 73 * 用户上线下线信息 74 * @param user 上线/下线 用户 75 * @param onLine 上线 还是 下线 76 */ 77 public static void setOnOffLineMsg(UserInfo user,boolean onLine){ 78 79 ArrayList<TeamInfo> teams = user.getTeams(); 80 for (TeamInfo teamInfo : teams) { 81 ArrayList<UserInfo> users = teamInfo.getFriendList(); 82 for (UserInfo userInfo : users) { 83 ServerTread st = null; 84 Iterator<UserInfo> other_users = stList.keySet().iterator(); 85 while (other_users.hasNext()) { 86 UserInfo obj = other_users.next(); 87 if (obj.getQq()== userInfo.getQq()) { 88 st = stList.get(obj); 89 } 90 } 91 if(st!=null){ 92 MsgHead msg = new MsgHead(); 93 msg.setTotalLen(4+1+4+4); 94 msg.setSrc(user.getQq()); 95 msg.setDest(userInfo.getQq()); 96 if(onLine) 97 msg.setType(MsgType.command_onLine); 98 else 99 msg.setType(MsgType.command_offLine); 100 st.sendMsg(msg); 101 } 102 } 103 } 104 105 } 106 107 /** 108 * 判断消息类型 并根据类型做出不同的响应 109 * @param user 发送者 110 * @param msg 消息内容 111 */ 112 public synchronized static void sendMsgToOther(UserInfo user,MsgHead msg) { 113 byte type = msg.getType(); 114 switch (type) { 115 //个人信息 116 case MsgType.command_perdata: 117 MsgPerData mpd = (MsgPerData) msg; 118 int perdata_len = 4+1+4+4+10+10+1; 119 mpd.setTotalLen(perdata_len); 120 mpd.setSrc(MsgType.SERVER_QQ_NUMBER); 121 mpd.setDest(user.getQq()); 122 mpd.setSex(user.getSex()); 123 mpd.setIcon(user.getIcon()); 124 mpd.setNickname(user.getNickname()); 125 126 stList.get(user).sendMsg(mpd); 127 break; 128 //放回好友列表 129 case MsgType.command_teamList: 130 MsgTeamList mtl = (MsgTeamList) msg; 131 int len = 4+1+4+4+4; 132 ArrayList<TeamInfo> teams = user.getTeams(); 133 TeamInfo newteams = new TeamInfo(""); 134 for (TeamInfo teamInfo : teams) { 135 int count = teamInfo.getFriendList().size(); 136 len += 10+1; 137 len += count*(10+4+10+1+1); 138 for (UserInfo userInfo : teamInfo.getFriendList()) { 139 userInfo = jdbc.getUser(userInfo.getQq()); 140 141 Set<UserInfo> users = stList.keySet(); 142 Iterator<UserInfo> its = users.iterator(); 143 while(its.hasNext()){ 144 UserInfo userInfo2 = its.next(); 145 if(userInfo.getQq()==userInfo2.getQq()){ 146 userInfo.setOnLine((byte)0); 147 } 148 } 149 newteams.addFriend(userInfo); 150 // if(stList.get(userInfo)!=null) 151 // userInfo.setOnLine((byte)0); //如果线程存在 则用户在线 152 } 153 } 154 teams.clear(); 155 teams.add(newteams); 156 mtl.setTotalLen(len); 157 mtl.setSrc(MsgType.SERVER_QQ_NUMBER); 158 mtl.setDest(user.getQq()); 159 mtl.setTeamList(teams); 160 161 stList.get(user).sendMsg(mtl); 162 break; 163 //查找在线的qq号 164 case MsgType.command_find: 165 ArrayList<UserInfo> frieads = user.getTeams().get(0).getFriendList(); 166 ArrayList<Integer> find_userqqs = new ArrayList<Integer>(); 167 for (int i = 0; i < frieads.size(); i++) { 168 find_userqqs.add(frieads.get(i).getQq()); 169 } 170 Set<UserInfo> users = stList.keySet(); 171 Iterator<UserInfo> its = users.iterator(); 172 MsgFindResp mfr = new MsgFindResp(); 173 mfr.setSrc(MsgType.SERVER_QQ_NUMBER); 174 mfr.setDest(user.getQq()); 175 mfr.setType(MsgType.command_find_resp); 176 while(its.hasNext()){ 177 UserInfo userInfo = its.next(); 178 System.out.println(frieads.size()+"aaaaaaaaaaaaaaaa "+frieads.contains(userInfo)); 179 if((userInfo.getQq()!=user.getQq())&&!(find_userqqs.contains(userInfo.getQq()))){ 180 mfr.addQq(userInfo); 181 } 182 } 183 int userCount = mfr.getUsers().size(); 184 mfr.setTotalLen(4+1+4+4+4+userCount*(4+10+10+1)); 185 186 stList.get(user).sendMsg(mfr); 187 break; 188 //添加好友 189 case MsgType.command_addFriend: 190 MsgAddFriend maf = (MsgAddFriend) msg; 191 MsgAddYou may = new MsgAddYou(); 192 may.setTotalLen(4+1+4+4+10+30+10); 193 may.setSrc(msg.getSrc()); 194 may.setDest(msg.getDest()); 195 may.setType(MsgType.command_addYou); 196 may.setNickname(user.getNickname()); 197 may.setNote(maf.getNote()); 198 may.setSex(user.getSex()); 199 200 //System.out.println("user.getNickname():"+user.getNickname()+" user.getSex():"+user.getSex()); 201 202 //向目标用户发送请求信息 203 //stList.get(UserDao.getUserInfo(user.getQq())).sendMsg(may); 204 Iterator<UserInfo> addFriend_users = stList.keySet().iterator(); 205 while (addFriend_users.hasNext()) { 206 UserInfo obj = addFriend_users.next(); 207 if (obj.getQq()== maf.getFriendQq()) { 208 stList.get(obj).sendMsg(may); 209 } 210 } 211 //stList.get(jdbc.getUser(maf.getFriendQq())).sendMsg(may); 212 break; 213 //有人添加你为好友 的 回复 214 case MsgType.command_addYouResp: 215 MsgAddYouResp mayr = (MsgAddYouResp) msg; 216 MsgAddFriendResp mafr = new MsgAddFriendResp(); 217 mafr.setTotalLen(4+1+4+4+1+4+10+10+1); 218 mafr.setSrc(mayr.getSrc()); 219 mafr.setDest(mayr.getDest()); 220 mafr.setType(MsgType.command_addFriend_Resp); 221 if(mayr.getState()==0){ //同意对方添加好友的请求 222 mafr.setState((byte) 0); //标记同意 223 jdbc.addFriend(msg.getSrc(), msg.getDest()); 224 jdbc.addFriend(msg.getDest(), msg.getSrc()); 225 //UserDao.addFriend(msg.getSrc(), msg.getDest(),"",""); 226 mafr.setQq(user.getQq()); 227 mafr.setNickName(user.getNickname()); 228 mafr.setSex(user.getSex()); 229 mafr.setIcon(user.getIcon()); 230 //stList.get(jdbc.getUser(mayr.getDest())).sendMsg(mafr); //向请求的那方 发送信息 231 Iterator<UserInfo> addYouResp_users = stList.keySet().iterator(); 232 while (addYouResp_users.hasNext()) { 233 UserInfo obj = addYouResp_users.next(); 234 if (obj.getQq()== mayr.getDest()) { 235 stList.get(obj).sendMsg(mafr); 236 } 237 } 238 239 UserInfo addYouResp_user = jdbc.getUser(mayr.getDest()); 240 mafr.setSrc(mayr.getDest()); 241 mafr.setDest(mayr.getSrc()); 242 mafr.setQq(addYouResp_user.getQq()); 243 mafr.setNickName(addYouResp_user.getNickname()); 244 mafr.setSex(addYouResp_user.getSex()); 245 mafr.setIcon(addYouResp_user.getIcon()); 246 //stList.get(user).sendMsg(mafr); //向同意的那方 发送信息 247 Iterator<UserInfo> addYouResp_users2 = stList.keySet().iterator(); 248 while (addYouResp_users2.hasNext()) { 249 UserInfo obj = addYouResp_users2.next(); 250 if (obj.getQq()== msg.getSrc()) { 251 stList.get(obj).sendMsg(mafr); 252 } 253 } 254 }else{ 255 mafr.setState((byte) 1); //标记不同意 256 //stList.get(jdbc.getUser(mayr.getDest())).sendMsg(mafr); 257 Iterator<UserInfo> other_users = stList.keySet().iterator(); 258 while (other_users.hasNext()) { 259 UserInfo obj = other_users.next(); 260 if (obj.getQq()== msg.getDest()) { 261 stList.get(obj).sendMsg(mafr); 262 } 263 } 264 } 265 266 break; 267 //震动窗口 268 case MsgType.command_vibration: 269 UserInfo vibration_user = jdbc.getUser(msg.getDest()); 270 Iterator<UserInfo> vibration_users = stList.keySet().iterator(); 271 while (vibration_users.hasNext()) { 272 UserInfo obj = vibration_users.next(); 273 if (obj.getQq()== vibration_user.getQq()) { 274 stList.get(obj).sendMsg(msg); 275 } 276 } 277 278 break; 279 //发送信息 及 文件 280 case MsgType.command_chatText: 281 case MsgType.command_chatFile: 282 UserInfo chat_user = jdbc.getUser(msg.getDest()); 283 Iterator<UserInfo> other_users = stList.keySet().iterator(); 284 while (other_users.hasNext()) { 285 UserInfo obj = other_users.next(); 286 if (obj.getQq()== chat_user.getQq()) { 287 stList.get(obj).sendMsg(msg); 288 } 289 } 290 291 break; 292 default: 293 break; 294 } 295 } 296 297 /** 298 * 随机验证码的生成方法 无用 299 * @return 验证码 300 */ 301 @SuppressWarnings("unused") 302 private String checkCode(){ 303 String code = ""; 304 Random random = new Random(); 305 for (int i = 0; i < 4; i++) { 306 random.nextInt(); 307 char c = (char) (random.nextInt(26)+97); 308 code += c; 309 } 310 311 return code; 312 } 313 }
1 package server; 2 3 import java.net.ServerSocket; 4 import java.net.Socket; 5 6 import tools.LogTools; 7 8 public class Server extends Thread { 9 10 private int port; // 服务器端口 11 12 public Server(int port) { 13 this.port = port; 14 } 15 16 @Override 17 public void run() { 18 try { 19 ServerSocket ss = new ServerSocket(port); 20 LogTools.INFO(this.getClass(), "服务器创建成功:" + port); 21 while (true) { 22 if (Thread.interrupted()) { 23 ServerThreadManage.removeClients(); 24 break; 25 } 26 Socket socket = ss.accept(); 27 if (Thread.interrupted()) { 28 ServerThreadManage.removeClients(); 29 break; 30 } 31 String CAdd = socket.getLocalSocketAddress().toString(); 32 LogTools.INFO(Server.class, "进入连结:" + CAdd); 33 ServerTread sc = new ServerTread(socket); 34 sc.start(); 35 } 36 37 } catch (Exception e) { 38 LogTools.ERROR(this.getClass(), "服务器创建失败:" + e); 39 } 40 } 41 }
tools包等同于上个项目的tools包
view包
1 package view; 2 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 6 import javax.swing.JButton; 7 import javax.swing.JFrame; 8 import javax.swing.JPanel; 9 10 import msg.MsgType; 11 import server.Server; 12 13 14 /*** 15 * 服务器界面 16 * @author Administrator 17 * 18 */ 19 public class ServerView extends JFrame implements ActionListener{ 20 21 private Server server; 22 private JPanel jp1; 23 private JButton start,stop; 24 25 public static void main(String[] args) { 26 new ServerView(); 27 } 28 29 public ServerView(){ 30 jp1 = new JPanel(); 31 start = new JButton("启动服务器"); 32 stop = new JButton("关闭服务器"); 33 34 start.addActionListener(this); 35 stop.addActionListener(this); 36 stop.setEnabled(false); 37 38 jp1.add(start); 39 jp1.add(stop); 40 this.add(jp1); 41 42 this.setSize(250, 80); 43 this.setVisible(true); 44 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 45 } 46 47 @Override 48 public void actionPerformed(ActionEvent arg0) { 49 if(arg0.getSource().equals(start)){ 50 start.setEnabled(false); 51 server = new Server(MsgType.serverPort); 52 server.start(); 53 stop.setEnabled(true); 54 }else if(arg0.getSource().equals(stop)){ 55 start.setEnabled(true); 56 server.interrupt(); 57 stop.setEnabled(false); 58 } 59 } 60 }
1 package com.langsin.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 7 public class JDBC { 8 private static String Username = "bigdata"; 9 private static String Passwd = "123"; 10 private static String Url = "jdbc:oracle:thin:@192.168.3.4:1521:ORCL";// 这个背过 jdbc去掉也可以 11 private static String Driver = "oracle.jdbc.driver.OracleDriver";// 这个背过 12 private static Connection Conn = null; 13 14 // 相当重要 代表与数据库的连接 15 public static Connection getinstance() { 16 try { 17 Class.forName(Driver); 18 Conn = DriverManager.getConnection(Url, Username, Passwd); 19 System.out.println("连接成功!!"); 20 } catch (ClassNotFoundException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } catch (SQLException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 } 27 return Conn; 28 } 29 public static void main(String[] args) { 30 Conn = JDBC.getinstance(); 31 } 32 }