我一直都想编一个自己的聊天软件,像QQ那种;最近有时间我就自己编了一个。编写的过程中收获很大……

现在拿出来跟大家分享,有兴趣的朋友可以和我交流交流。

先给大家看一下效果:

启动服务器:

再给大家看一下简陋的登录窗口/(ㄒoㄒ)/~~输入密码登录:

终于进入主题了O(∩_∩)O!客户端主界面:

Mary给Yuan发一个消息:

Yuan打开消息框进行回复:

我们再来看一下群发功能,群发首先得多叫几个好友上线,要不谁知道他们有没有收到……

188的好友们先把队形站好,接下来就等着188给你们发消息吧

这时候老大就要登场准备讲话了:

假设Marry有一天新认识一个好基友,那怎么添加好友呢?接下给给大家看一看添加好友功能:

那个陌生的好基友从哪来呢?不如现造一个(注册用户):

登录小花,Mary再添加小花为好友:

点击添加好友按钮,输入对方账号:

基友花花收到好友请求后,好友请求按钮就会被点亮,如果没有好友请求的话,这个按钮是失效的。

花花现在需要做的就是同意添加好友,当然,花花也有权拒绝,但是突然有妹子加好友,花花怎么会拒绝呢,\(^o^)/~。

同意,Marry和花花就能开心地聊天了。

还有离线消息没给大家贴图:相比大家也看腻了吧,贴了这么多图,唯一的感触就是window的蓝色主题背景还真的挺好看的。O(∩_∩)O哈!

技术细节:

我编写的这个软件分三步分组成:数据库部分、服务器部分、客户端部分。实现的过程中采用MVC模式。

整个系统中的核心部分在于服务器端接收用户请求、解析请求、处理请求;客户端接收服务器消息、解析消息、处理并显示消息。

下面定义了本系统客户端与服务器端通信的请求码:

客户端请求码与服务器返回结果:
  00:登录  例如:00:123,123    表示用户账号123,密码123请求登录;登录成功服务器会给客户端发送:

>>>00:123,123

>>>001:123,Tom;120,Yuan;124,John;&$119,123;&$120,123,2016-9-11 15:24:11,你好;120,123,2016-9-11 15:25:11,你好;120,123,2016-9-11 15:26:11,你好;

返回的信息被&$分成三段,第一段表示用户本身与好友列表,第二字段表示收到119申请添加好友的请求,第三段表示离线消息。每段内的记录以‘;’分隔;每条记录里的参数以‘,’分隔;

  10:查询与指定好友的历史消息  10:120,119   表示查询120与119的聊天记录;返回示例:

>>>10,120,119

>>>101:120,119,2016-1-12 0:00:00,hello;120,119,2016-8-10 0:00:00,你好;120,119,2016-8-10 0:00:00,你好,我是120;120,119,2016-8-10
0:00:00,nihao;120,119,2016-8-10 0:00:00,nihao;120,119,2016-8-10 0:00:00,nihao;120,119,2016-8-10 0:00:00,213213;119,120,
2016-8-10 0:00:00,你好;119,120,2016-8-10 0:00:00,hello;119,120,2016-8-10 0:00:00,Hi;119,120,2016-8-10 0:00:00,hello
;119,120,2016-8-10 0:00:00,hi;119,120,2016-8-10 0:00:00,哈哈;    每条历史消息以‘;’为间隔。

  11:点对点发msg  11:120,119,2016-7-16 10:10:10,hello    表示120给119发送点对点消息“hello”,时间为2016-7-16 10:10:10
  12:群发好友msg  12:120,120,2016-7-16 11:11:11,大家好,我是120   表示120给所有好友群发消息,与点对点发消息有所不同的是这里的接收方发送方都是自己账号;
  13:删除历史消息  13:120,119  表示120请求删除与119的聊天记录;这里需要注意的一点是,用户删除聊天记录是仅仅是把数据库中消息表中的d字段置0了,用户查询历史聊天记录时也会检查d字段,对于那些d字段为0的消息是检索不到的,就好像自己把它已经删除了一样;
  20:获得好友列表  20:120  表示请求120的好友列表

>>>20:120
>>>201:122,Yaze;123,Tom;130,M; 

  21:添加好友  21:120,130   表示120请求添加130为好友,服务器端就会根据可以请求在数据库表failrelation(未确认好友关系表)中创建一条记录;
  22:删除好友  22:120,119  表示120删除好友119,服务器端根据请求会在relation表中删除相应记录,并对在用用户进行通知;
  23:确认添加好友  23:130,120   表示130同意添加120为好友,服务器端会删除相应的failrelation记录,并在relation中添加一个记录(添加时调整id顺序,使其检索方便,这里是使数值小的id放在前面);

  24:拒绝添加好友
  30:更改用户名  30:120,Yozane,120  表示把账号120的用户名更改为Yozane,返回修改后的用户信息

>>>30:152,jiaGu,170
>>>301:152,jiaGu,170

  31:更改用户密码   30:120,新密码,旧密码

>>>31:152,152,170
>>>301:152,jiaGu,152

  40:注册新用户   40:Tommy,130  表示申请注册用户名为Tommy,密码为130的用户。

示例:

>>>40:Jia,170
>>>401:152,Jia,170

数据库转储文件(结构与数据)数据库名为superqq:

  1. /*
  2. Navicat MySQL Data Transfer
  3.  
  4. Source Server : courseregis
  5. Source Server Version : 50022
  6. Source Host : localhost:3306
  7. Source Database : superqq
  8.  
  9. Target Server Type : MYSQL
  10. Target Server Version : 50022
  11. File Encoding : 65001
  12.  
  13. Date: 2016-07-21 21:46:12
  14. */
  15.  
  16. SET FOREIGN_KEY_CHECKS=0;
  17.  
  18. -- ----------------------------
  19. -- Table structure for failmessage
  20. -- ----------------------------
  21. DROP TABLE IF EXISTS `failmessage`;
  22. CREATE TABLE `failmessage` (
  23. `id1` bigint(10) NOT NULL,
  24. `id2` bigint(10) default NULL,
  25. `time` datetime default NULL,
  26. `content` varchar(140) default NULL,
  27. `id` bigint(20) NOT NULL auto_increment,
  28. PRIMARY KEY (`id`),
  29. KEY `f3` USING BTREE (`id1`),
  30. KEY `f4` USING BTREE (`id2`),
  31. CONSTRAINT `failmessage_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  32. CONSTRAINT `failmessage_ibfk_2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
  33. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='InnoDB free: 3072 kB; (`id1`) REFER `superqq/user`(`id`) ON ';
  34.  
  35. -- ----------------------------
  36. -- Records of failmessage
  37. -- ----------------------------
  38. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 10:52:17', '你好', '');
  39. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 10:52:17', '你好', '');
  40. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:43:17', '你好', '');
  41. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:43:17', '你好', '');
  42. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
  43. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
  44. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
  45. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
  46. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:48:17', '大家好', '');
  47. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '');
  48. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '');
  49. INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:56:17', '你好', '');
  50. INSERT INTO `failmessage` VALUES ('', '', '2016-08-18 07:55:18', 'NIHAO', '');
  51. INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
  52. INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
  53. INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
  54. INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
  55.  
  56. -- ----------------------------
  57. -- Table structure for failrelation
  58. -- ----------------------------
  59. DROP TABLE IF EXISTS `failrelation`;
  60. CREATE TABLE `failrelation` (
  61. `id1` bigint(10) NOT NULL,
  62. `id2` bigint(10) NOT NULL,
  63. PRIMARY KEY (`id1`,`id2`),
  64. KEY `f2` USING BTREE (`id2`),
  65. CONSTRAINT `failrelation_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  66. CONSTRAINT `failrelation_ibfk_2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
  67. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='InnoDB free: 3072 kB; (`id1`) REFER `superqq/user`(`id`) ON ';
  68.  
  69. -- ----------------------------
  70. -- Records of failrelation
  71. -- ----------------------------
  72. INSERT INTO `failrelation` VALUES ('', '');
  73. INSERT INTO `failrelation` VALUES ('', '');
  74. INSERT INTO `failrelation` VALUES ('', '');
  75. INSERT INTO `failrelation` VALUES ('', '');
  76.  
  77. -- ----------------------------
  78. -- Table structure for message
  79. -- ----------------------------
  80. DROP TABLE IF EXISTS `message`;
  81. CREATE TABLE `message` (
  82. `id1` bigint(10) NOT NULL,
  83. `id2` bigint(10) NOT NULL,
  84. `time` datetime NOT NULL,
  85. `content` varchar(140) NOT NULL,
  86. `id` bigint(20) NOT NULL auto_increment,
  87. `d1` bit(1) default '',
  88. `d2` bit(1) default '',
  89. PRIMARY KEY (`id`),
  90. KEY `f3` (`id1`),
  91. KEY `f4` (`id2`),
  92. CONSTRAINT `f3` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
  93. CONSTRAINT `f4` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
  94. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  95.  
  96. -- ----------------------------
  97. -- Records of message
  98. -- ----------------------------
  99. INSERT INTO `message` VALUES ('', '', '2016-07-07 10:42:13', 'hello 120 I\'m 119', '1', '', '\0');
  100. INSERT INTO `message` VALUES ('121', '120', '2016-07-06 10:42:37', 'hello 120 I\'m 121', '', '', '\0');
  101. INSERT INTO `message` VALUES ('', '', '2016-08-04 10:43:09', 'hello 123 I\'m 120', '3', '', '');
  102. INSERT INTO `message` VALUES ('120', '119', '2017-12-09 00:00:00', 'test insert time.', '4', '\0', '');
  103. INSERT INTO `message` VALUES ('119', '120', '2016-07-27 14:00:48', 'hello ', '5', '', '\0');
  104. INSERT INTO `message` VALUES ('119', '120', '2016-07-31 14:01:10', 'hello', '6', '', '\0');
  105. INSERT INTO `message` VALUES ('120', '119', '2016-07-08 15:39:49', 'hello', '7', '\0', '');
  106. INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:43:53', 'hello test date', '8', '', '\0');
  107. INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:45:59', 'hello test date', '9', '', '\0');
  108. INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:46:08', 'hello test date', '10', '', '\0');
  109. INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:46:43', 'hello test date', '11', '', '\0');
  110. INSERT INTO `message` VALUES ('120', '124', '2016-07-22 17:47:53', '', '12', '', '');
  111. INSERT INTO `message` VALUES ('120', '119', '2015-03-03 12:13:14', 'nihao', '13', '\0', '');
  112. INSERT INTO `message` VALUES ('120', '119', '2016-10-08 10:12:11', '120群发信息。', '14', '\0', '');
  113. INSERT INTO `message` VALUES ('120', '119', '2016-08-10 14:05:10', '213213', '15', '', '');
  114. INSERT INTO `message` VALUES ('119', '120', '2016-08-10 17:34:10', '你好--', '18', '', '');
  115. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:37:10', 'hHh', '', '', '');
  116. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:39:10', 'HH', '', '', '');
  117. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:42:10', '而且为二次', '', '', '');
  118. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:43:10', '年后', '', '', '');
  119. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:46:10', '哈哈', '', '', '');
  120. INSERT INTO `message` VALUES ('', '', '2016-08-10 17:49:10', '哈哈', '', '', '');
  121. INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:11', 'nihao', '', '', '');
  122. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:12:10', '你好', '', '', '');
  123. INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
  124. INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
  125. INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
  126. INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
  127. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:20:10', '你好', '', '', '');
  128. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:21:10', '年号', '', '', '');
  129. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:22:10', 'niaoj', '', '', '');
  130. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:22:10', '', '', '', '');
  131. INSERT INTO `message` VALUES ('', '', '2016-08-10 18:25:10', '你好', '', '', '');
  132. INSERT INTO `message` VALUES ('', '', '2016-08-10 19:16:10', 'NIHAO', '', '', '');
  133. INSERT INTO `message` VALUES ('', '', '2016-08-10 19:16:10', 'NIHAO', '', '', '');
  134. INSERT INTO `message` VALUES ('', '', '2016-08-10 19:43:10', 'njkfds', '', '', '');
  135. INSERT INTO `message` VALUES ('', '', '2016-08-10 19:43:10', 'fjskadljf dsa', '', '', '');
  136. INSERT INTO `message` VALUES ('', '', '2016-08-11 10:44:11', '你哈', '', '', '');
  137. INSERT INTO `message` VALUES ('', '', '2016-08-11 10:45:11', '哈哈', '', '', '');
  138. INSERT INTO `message` VALUES ('', '', '2016-08-11 10:45:11', '你好哈', '', '', '');
  139. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:12:11', '你好', '', '', '');
  140. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:13:11', '我很好', '', '', '');
  141. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:13:11', '年号', '', '', '');
  142. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:14:11', '大家好', '', '', '');
  143. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:14:11', '你好O', '', '', '');
  144. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:29:11', '你好', '', '', '');
  145. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:29:11', '你好', '', '', '');
  146. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你好', '', '', '');
  147. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你好', '', '', '');
  148. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你哈', '', '', '');
  149. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '好', '', '', '');
  150. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '好', '', '', '');
  151. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '恩', '', '', '');
  152. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '哈哈', '', '', '');
  153. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '你好', '', '', '');
  154. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '地方', '', '', '');
  155. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '发', '', '', '');
  156. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:38:11', '年后', '', '', '');
  157. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:40:11', '年后', '', '', '');
  158. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:42:11', '你好', '', '', '');
  159. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:47:11', '你好', '', '', '');
  160. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:49:11', '你好', '', '', '');
  161. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你哈', '', '', '');
  162. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
  163. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
  164. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', ' 你好', '', '', '');
  165. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
  166. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  167. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  168. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  169. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  170. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  171. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  172. INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
  173. INSERT INTO `message` VALUES ('', '', '2016-08-11 14:56:11', '大家好我是Yuan', '', '', '');
  174. INSERT INTO `message` VALUES ('', '', '2016-08-11 14:59:11', '大家好', '', '', '');
  175. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你好', '', '', '');
  176. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你好', '', '', '');
  177. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你哈', '', '', '');
  178. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '表', '', '', '');
  179. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:26:11', '你哈', '', '', '');
  180. INSERT INTO `message` VALUES ('', '', '2016-08-11 15:28:11', '大家好', '', '', '');
  181. INSERT INTO `message` VALUES ('', '', '2016-01-12 10:10:12', 'hello', '', '', '');
  182. INSERT INTO `message` VALUES ('', '', '2016-08-08 10:02:08', 'hello', '', '', '');
  183. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:12:12', 'hello', '', '', '');
  184. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
  185. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
  186. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
  187. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
  188. INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
  189. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:02:17', 'hello', '', '', '');
  190. INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
  191. INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
  192. INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
  193. INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
  194. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:03:17', 'hello', '', '', '');
  195. INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
  196. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:05:17', '大家好我是120', '', '', '');
  197. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:06:17', '大家好', '', '', '');
  198. INSERT INTO `message` VALUES ('', '', '2017-01-01 05:04:01', '大家好', '', '', '');
  199. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:09:17', '大家好', '', '', '');
  200. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:09:17', '大家好', '', '', '');
  201. INSERT INTO `message` VALUES ('', '', '2016-08-17 10:41:17', '你好', '', '', '');
  202. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
  203. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
  204. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
  205. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
  206. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
  207. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
  208. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '大家好', '', '', '');
  209. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '大家好', '', '', '');
  210. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:31:17', '你好', '', '', '');
  211. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:40:17', '你好', '', '', '');
  212. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:40:17', '你好', '', '', '');
  213. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
  214. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
  215. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
  216. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
  217. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:42:17', '不好', '', '', '');
  218. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:42:17', '你好', '', '', '');
  219. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:43:17', '你好', '', '', '');
  220. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:43:17', '我是119', '', '', '');
  221. INSERT INTO `message` VALUES ('', '', '2016-08-17 11:51:17', '你好', '', '', '');
  222. INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
  223. INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
  224. INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
  225. INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
  226. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:42:17', '你好', '', '', '');
  227. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:42:17', '你好', '', '', '');
  228. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  229. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  230. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  231. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  232. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  233. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
  234. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  235. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  236. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  237. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  238. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  239. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  240. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
  241. INSERT INTO `message` VALUES ('', '', '2017-01-01 05:04:01', '大家好', '', '', '');
  242. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:48:17', '大家好', '', '', '');
  243. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
  244. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
  245. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
  246. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
  247. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:55:17', '你好', '', '', '');
  248. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:56:17', '你好', '', '', '');
  249. INSERT INTO `message` VALUES ('', '', '2016-08-17 14:56:17', '你好', '', '', '');
  250. INSERT INTO `message` VALUES ('', '', '2016-08-18 07:53:18', 'NIHAO', '', '', '');
  251. INSERT INTO `message` VALUES ('', '', '2016-08-18 07:55:18', 'NIHAO', '', '', '');
  252. INSERT INTO `message` VALUES ('', '', '2016-08-18 07:55:18', 'NIAHO', '', '', '');
  253. INSERT INTO `message` VALUES ('', '', '2016-08-18 07:56:18', '你好', '', '', '');
  254. INSERT INTO `message` VALUES ('', '', '2016-08-21 11:24:21', '你好', '', '', '');
  255. INSERT INTO `message` VALUES ('', '', '2016-08-21 11:28:21', '你好', '', '', '');
  256. INSERT INTO `message` VALUES ('', '', '2016-08-21 12:08:21', '你好', '', '', '');
  257. INSERT INTO `message` VALUES ('', '', '2016-08-21 12:56:21', '你好', '', '', '');
  258. INSERT INTO `message` VALUES ('', '', '2016-08-21 15:10:21', '你好', '', '', '');
  259. INSERT INTO `message` VALUES ('', '', '2016-08-21 15:11:21', '你好', '', '', '');
  260. INSERT INTO `message` VALUES ('', '', '2016-08-21 20:51:21', '你好,我是Mary', '', '', '');
  261. INSERT INTO `message` VALUES ('', '', '2016-08-21 20:55:21', '收到,我是Yuan', '', '', '');
  262. INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
  263. INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
  264. INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
  265. INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
  266.  
  267. -- ----------------------------
  268. -- Table structure for relation
  269. -- ----------------------------
  270. DROP TABLE IF EXISTS `relation`;
  271. CREATE TABLE `relation` (
  272. `id1` bigint(10) NOT NULL,
  273. `id2` bigint(10) NOT NULL,
  274. PRIMARY KEY (`id1`,`id2`),
  275. KEY `f2` (`id2`),
  276. CONSTRAINT `f1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  277. CONSTRAINT `f2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
  278. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  279.  
  280. -- ----------------------------
  281. -- Records of relation
  282. -- ----------------------------
  283. INSERT INTO `relation` VALUES ('', '');
  284. INSERT INTO `relation` VALUES ('', '');
  285. INSERT INTO `relation` VALUES ('', '');
  286. INSERT INTO `relation` VALUES ('', '');
  287. INSERT INTO `relation` VALUES ('', '');
  288. INSERT INTO `relation` VALUES ('', '');
  289. INSERT INTO `relation` VALUES ('', '');
  290. INSERT INTO `relation` VALUES ('', '');
  291. INSERT INTO `relation` VALUES ('', '');
  292. INSERT INTO `relation` VALUES ('', '');
  293. INSERT INTO `relation` VALUES ('', '');
  294. INSERT INTO `relation` VALUES ('', '');
  295. INSERT INTO `relation` VALUES ('', '');
  296. INSERT INTO `relation` VALUES ('', '');
  297. INSERT INTO `relation` VALUES ('', '');
  298. INSERT INTO `relation` VALUES ('', '');
  299. INSERT INTO `relation` VALUES ('', '');
  300. INSERT INTO `relation` VALUES ('', '');
  301. INSERT INTO `relation` VALUES ('', '');
  302. INSERT INTO `relation` VALUES ('', '');
  303. INSERT INTO `relation` VALUES ('', '');
  304. INSERT INTO `relation` VALUES ('', '');
  305. INSERT INTO `relation` VALUES ('', '');
  306. INSERT INTO `relation` VALUES ('', '');
  307. INSERT INTO `relation` VALUES ('', '');
  308. INSERT INTO `relation` VALUES ('', '');
  309. INSERT INTO `relation` VALUES ('', '');
  310. INSERT INTO `relation` VALUES ('', '');
  311. INSERT INTO `relation` VALUES ('', '');
  312. INSERT INTO `relation` VALUES ('', '');
  313. INSERT INTO `relation` VALUES ('', '');
  314. INSERT INTO `relation` VALUES ('', '');
  315. INSERT INTO `relation` VALUES ('', '');
  316. INSERT INTO `relation` VALUES ('', '');
  317. INSERT INTO `relation` VALUES ('', '');
  318. INSERT INTO `relation` VALUES ('', '');
  319. INSERT INTO `relation` VALUES ('', '');
  320. INSERT INTO `relation` VALUES ('', '');
  321. INSERT INTO `relation` VALUES ('', '');
  322. INSERT INTO `relation` VALUES ('', '');
  323. INSERT INTO `relation` VALUES ('', '');
  324. INSERT INTO `relation` VALUES ('', '');
  325. INSERT INTO `relation` VALUES ('', '');
  326.  
  327. -- ----------------------------
  328. -- Table structure for user
  329. -- ----------------------------
  330. DROP TABLE IF EXISTS `user`;
  331. CREATE TABLE `user` (
  332. `id` bigint(10) NOT NULL auto_increment,
  333. `name` varchar(20) default NULL,
  334. `pwd` varchar(32) NOT NULL,
  335. PRIMARY KEY (`id`)
  336. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  337.  
  338. -- ----------------------------
  339. -- Records of user
  340. -- ----------------------------
  341. INSERT INTO `user` VALUES ('', 'Jiaxin', '7e1cd7dca89a1678042477183b7ac3f');
  342. INSERT INTO `user` VALUES ('', 'Yuan', 'c6f057b86584942e415435ffb1fa93d4');
  343. INSERT INTO `user` VALUES ('', 'Xuewei', '4c56ff4ce4aaf9573aa5dff913df997a');
  344. INSERT INTO `user` VALUES ('', 'Yaze', 'a0a080f42e6f13b3a2df133f073095dd');
  345. INSERT INTO `user` VALUES ('', 'Tom', '202cb962ac59075b964b07152d234b70');
  346. INSERT INTO `user` VALUES ('', 'John', 'c8ffe9a587b126f152ed3d89a146b445');
  347. INSERT INTO `user` VALUES ('', 'Yunchen', '3def184ad8f4755ff269862ea77393dd');
  348. INSERT INTO `user` VALUES ('', 'M', '9b8619251a19057cff70779273e95aa6');
  349. INSERT INTO `user` VALUES ('', 'Silly', '65ded5353c5ee48d0b7d48c591b8f430');
  350. INSERT INTO `user` VALUES ('', 'Tikky', '9fc3d7152ba9336a670e36d0ed79bc43');
  351. INSERT INTO `user` VALUES ('', '', '1385974ed5904a438616ff7bdb3f7439');
  352. INSERT INTO `user` VALUES ('', 'Mary', '7ef605fc8dba5425d6965fbd4c8fbe1f');
  353. INSERT INTO `user` VALUES ('', 'Yane', 'b73ce398c39f506af761d2277d853a92');
  354. INSERT INTO `user` VALUES ('', 'jiaGu', '37a749d808e46495a8da1e5352d03cae');
  355. INSERT INTO `user` VALUES ('', 'YY', 'da4fb5c6e93e74d3df8527599fa62642');
  356. INSERT INTO `user` VALUES ('', 'Yane', '202cb962ac59075b964b07152d234b70');
  357. INSERT INTO `user` VALUES ('', 'Yanem', '202cb962ac59075b964b07152d234b70');
  358. INSERT INTO `user` VALUES ('', 'Y', '202cb962ac59075b964b07152d234b70');
  359. INSERT INTO `user` VALUES ('', 'YY', '202cb962ac59075b964b07152d234b70');
  360. INSERT INTO `user` VALUES ('', 'ZZ', '202cb962ac59075b964b07152d234b70');
  361. INSERT INTO `user` VALUES ('', 'X', '202cb962ac59075b964b07152d234b70');
  362. INSERT INTO `user` VALUES ('', 'X', '202cb962ac59075b964b07152d234b70');
  363. INSERT INTO `user` VALUES ('', 'te', '202cb962ac59075b964b07152d234b70');
  364. INSERT INTO `user` VALUES ('', 'Marry', '202cb962ac59075b964b07152d234b70');
  365. INSERT INTO `user` VALUES ('', 'Marry', '202cb962ac59075b964b07152d234b70');
  366. INSERT INTO `user` VALUES ('', 'Gray', '202cb962ac59075b964b07152d234b70');
  367. INSERT INTO `user` VALUES ('', 'Y', '202cb962ac59075b964b07152d234b70');
  368. INSERT INTO `user` VALUES ('', 'Velly', '202cb962ac59075b964b07152d234b70');
  369. INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
  370. INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
  371. INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
  372. INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
  373. INSERT INTO `user` VALUES ('', 'Harry', 'c20ad4d76fe97759aa27a0c99bff6710');
  374. INSERT INTO `user` VALUES ('', 'Harray', '202cb962ac59075b964b07152d234b70');
  375. INSERT INTO `user` VALUES ('', 'Hyne', '202cb962ac59075b964b07152d234b70');
  376. INSERT INTO `user` VALUES ('', 'Hyne', '202cb962ac59075b964b07152d234b70');
  377. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  378. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  379. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  380. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  381. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  382. INSERT INTO `user` VALUES ('', 'Tedr', '202cb962ac59075b964b07152d234b70');
  383. INSERT INTO `user` VALUES ('', 'Tedr', '202cb962ac59075b964b07152d234b70');
  384. INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
  385. INSERT INTO `user` VALUES ('', 'YaneZane', '202cb962ac59075b964b07152d234b70');
  386. INSERT INTO `user` VALUES ('', 'YaneZanen', '202cb962ac59075b964b07152d234b70');
  387. INSERT INTO `user` VALUES ('', 'Trne', '202cb962ac59075b964b07152d234b70');
  388. INSERT INTO `user` VALUES ('', 'Tone', '202cb962ac59075b964b07152d234b70');
  389. INSERT INTO `user` VALUES ('', 'Mary', '202cb962ac59075b964b07152d234b70');
  390. INSERT INTO `user` VALUES ('', 'Hery', '202cb962ac59075b964b07152d234b70');
  391. INSERT INTO `user` VALUES ('', 'Tommas', '202cb962ac59075b964b07152d234b70');
  392. INSERT INTO `user` VALUES ('', 'Johnson', '202cb962ac59075b964b07152d234b70');
  393. INSERT INTO `user` VALUES ('', '刘远圳', '202cb962ac59075b964b07152d234b70');
  394. INSERT INTO `user` VALUES ('', 'Torrorrent', '202cb962ac59075b964b07152d234b70');
  395. INSERT INTO `user` VALUES ('', '基友小花', '202cb962ac59075b964b07152d234b70');

数据库操作类dao.java:

  1. package dao;
  2.  
  3. import java.math.BigInteger;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.util.Date;
  12. import java.util.GregorianCalendar;
  13. import java.util.LinkedList;
  14. import java.util.List;
  15. import java.util.Vector;
  16.  
  17. import model.message;
  18. import model.relation;
  19. import model.user;
  20. public class dao{
  21. static String username="root";
  22. static String pwd = "";
  23. static String url = "jdbc:mysql://127.0.0.1:3306/superqq";
  24. static String driver = "org.gjt.mm.mysql.Driver";
  25. static Connection con;
  26. static Statement statement;
  27. public dao(){}
  28. public static void main(String[] args){
  29. dao d = new dao();
  30. }
  31. private static Date convertToDate(String str){//用于将sql.date转化为util.date
  32. String[] li = str.split(" ");
  33. if(li.length!=2){
  34. System.out.println("converToDate 出错,空格错误");
  35. return new Date();
  36. }
  37. String[] para = li[0].split("-");
  38. String[] para1 = li[1].split(":");
  39. return new GregorianCalendar(new Integer(para[0]).intValue(),new Integer(para[1]).intValue(),new Integer(para[2]).intValue(),new Integer(para1[0]).intValue(),new Integer(para1[1]).intValue(),new Integer(para[2]).intValue()).getTime();
  40. }
  41. private void start(){
  42. try {
  43. Class.forName( driver );
  44. } catch (ClassNotFoundException e) {
  45. // TODO Auto-generated catch block
  46. System.out.println("error in loading driver.");
  47. }
  48. try {
  49. con = DriverManager.getConnection(url,username,pwd);
  50. statement = con.createStatement();
  51. } catch (SQLException e) {
  52. // TODO Auto-generated catch block
  53. System.out.println("error in connect database.");
  54. }
  55. }
  56. private void close(){
  57. try {
  58. statement.close();
  59. } catch (SQLException e) {
  60. // TODO Auto-generated catch block
  61. System.out.println("error in close statement.");
  62. }
  63. try {
  64. con.close();
  65. } catch (SQLException e) {
  66. // TODO Auto-generated catch block
  67. System.out.println("error in close connection.");
  68. }
  69. }
  70. public user getUser(String id){
  71. start();
  72. List<user> li = new LinkedList<user>();
  73. try {
  74. ResultSet re = statement.executeQuery("select * from user where id ="+id+";");
  75. while(re.next()){
  76. li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
  77. }
  78. } catch (SQLException e) {
  79. // TODO Auto-generated catch block
  80. System.out.println("error in getUser("+id+")");
  81. }
  82. finally{close();}
  83. return li.get(0);
  84. }
  85. public user getUser(String name,String pwd){
  86. start();
  87. List<user> li = new LinkedList<user>();
  88. try {
  89. ResultSet re = statement.executeQuery("select * from user where name ='"+name+"';");
  90. while(re.next()){
  91. li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
  92. }
  93. } catch (SQLException e) {
  94. // TODO Auto-generated catch block
  95. System.out.println("error in getUser("+name+","+pwd+")");
  96. }
  97. finally{close();}
  98. if(li.size()!=0){
  99. return li.get(0);
  100. }else{
  101. return null;
  102. }
  103. }
  104. public List<relation> getRelation(String id){
  105. start();
  106. List<relation> li = new LinkedList<relation>();
  107. try {
  108. statement = con.createStatement();
  109. ResultSet re = statement.executeQuery("select * from relation where id1 ="+id+"||id2 ="+id+";");
  110. while(re.next()){
  111. li.add(new relation(re.getString(1),re.getString(2)));
  112. }
  113. } catch (SQLException e) {
  114. // TODO Auto-generated catch block
  115. System.out.println("error in getRelation("+id+")");
  116. }
  117. finally{close();}
  118. return li;
  119. }
  120.  
  121. public List<user> getUserList(){
  122. start();
  123. List<user> li=new LinkedList<user>();
  124. ResultSet re;
  125. try {
  126. re = statement.executeQuery("select * from user;");
  127. while(re.next()){
  128. li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
  129. }
  130. } catch (SQLException e) {
  131. // TODO Auto-generated catch block
  132. e.printStackTrace();
  133. }
  134. finally{close();}
  135. return li;
  136. }
  137. public Boolean addUser(user u){
  138. start();
  139. Boolean flag = true;
  140. try {
  141. statement.execute("insert into user(name,pwd) values('"+u.getUsername()+"','"+u.getPwd()+"');");
  142. } catch (SQLException e) {
  143. // TODO Auto-generated catch block
  144. System.out.println("error in addUser:"+u);
  145. flag = false;
  146. }
  147. finally{close();}
  148. return flag;
  149. }
  150. public Boolean deleteUser(String id){
  151. start();
  152. Boolean flag = true;
  153. try {
  154. statement.execute("delete from user where id ='"+id+"';");
  155. } catch (SQLException e) {
  156. // TODO Auto-generated catch block
  157. System.out.println("error in deleteUser:id="+id);
  158. flag = false;
  159. }
  160. finally{close();}
  161. return flag;
  162. }
  163. public Boolean updateUser(user u){
  164. start();
  165. Boolean flag=true;
  166. try {
  167. statement.execute("update user set name='"+u.getUsername()+"',pwd ='"+u.getPwd()+"' where id ='"+u.getId()+"';");
  168. } catch (SQLException e) {
  169. // TODO Auto-generated catch block
  170. System.out.println("error in update:"+u);
  171. flag = false;
  172. }
  173. finally{close();}
  174. return flag;
  175. }
  176. public Boolean updatePwd(user u){
  177. start();
  178. Boolean flag=true;
  179. try {
  180. statement.execute("update user set pwd='"+u.getUsername()+"' where id ='"+u.getId()+"';");
  181. } catch (SQLException e) {
  182. // TODO Auto-generated catch block
  183. System.out.println("error in updatepwd:"+u);
  184. flag = false;
  185. }
  186. finally{close();}
  187. return flag;
  188. }
  189. public List<relation> getRelation(){
  190. start();
  191. List<relation> li=new LinkedList<relation>();
  192. ResultSet re;
  193. try {
  194. re = statement.executeQuery("select * from relation;");
  195. while(re.next()){
  196. li.add(new relation(re.getString(1),re.getString(2)));
  197. }
  198. } catch (SQLException e) {
  199. // TODO Auto-generated catch block
  200. System.out.println("error in getRelation().");
  201. }
  202. finally{close();}
  203. return li;
  204. }
  205. public Boolean addRelation(relation r){//先对id1,id2排序,再插入
  206. start();
  207. Boolean flag = true;
  208. try {
  209. String id1 = r.getId1();
  210. String id2 = r.getId2();
  211. if(new Integer(id1).intValue()>new Integer(id2).intValue()){
  212. String id = id1;
  213. id1 = id2;
  214. id2 = id;
  215. }
  216. statement.execute("insert into relation(id1,id2) values('"+id1+"','"+id2+"');");
  217. } catch (SQLException e) {
  218. // TODO Auto-generated catch block
  219. System.out.println("error in addRelation:"+r);
  220. flag = false;
  221. }
  222. finally{close();}
  223. return flag;
  224. }
  225. public Boolean deleteRelation(relation r){//确保id有序(非减)
  226. start();
  227. Boolean flag = true;
  228. try {
  229. String id1 = r.getId1();
  230. String id2 = r.getId2();
  231. if(new Integer(id1).intValue()>new Integer(id2).intValue()){
  232. String id = id1;
  233. id1 = id2;
  234. id2 = id;
  235. }
  236. statement.execute("delete from relation where id1 = '"+id1+"'&&id2 ='"+id2+"';");
  237. } catch (SQLException e) {
  238. // TODO Auto-generated catch block
  239. System.out.println("error in deleteRelation("+r+").");
  240. flag = false;
  241. }
  242. finally{close();}
  243. return flag;
  244. }
  245. public List<relation> getFailRelation(String id){
  246. start();
  247. List<relation> li=new LinkedList<relation>();
  248. ResultSet re;
  249. try {
  250. re = statement.executeQuery("select * from failrelation where id2 = '"+id+"';");
  251. while(re.next()){
  252. li.add(new relation(re.getString(1),re.getString(2)));
  253. }
  254. } catch (SQLException e) {
  255. // TODO Auto-generated catch block
  256. System.out.println("error in getFailRelation:id="+id);
  257. }
  258. finally{close();}
  259. return li;
  260. }
  261. public Boolean addFailRelation(relation r){
  262. start();
  263. Boolean flag =true;
  264. try {
  265. statement.execute("insert into failrelation(id1,id2) values('"+r.getId1()+"','"+r.getId2()+"');");
  266. } catch (SQLException e) {
  267. // TODO Auto-generated catch block
  268. System.out.println("error in addFailRelation("+r+").");
  269. flag = false;
  270. }
  271. finally{close();}
  272. return flag;
  273. }
  274. public Boolean deleteFailRelation(relation r){
  275. start();
  276. Boolean flag = true;
  277. try {
  278. statement.execute("delete from failrelation where (id1='"+r.getId1()+"'&&id2 ='"+r.getId2()+"')||(id1='"+r.getId2()+"'&&id2='"+r.getId1()+"');");
  279. } catch (SQLException e) {
  280. // TODO Auto-generated catch block
  281. System.out.println("error in deleteFailRelation("+r+").");
  282. flag = false;
  283. }
  284. finally{close();}
  285. return flag;
  286. }
  287. public List<user> getFriend(String id){
  288. start();
  289. List<user> li=new LinkedList<user>();
  290. ResultSet re;
  291. try {
  292. re = statement.executeQuery("select user.id,user.name from user,relation where (relation.id1 = '"+id+"'&&relation.id2 = user.id )||(relation.id2 = '"+id+"'&&relation.id1 = user.id);");
  293. while(re.next()){
  294. li.add(new user(re.getString(1),re.getString(2)));
  295. }
  296. } catch (SQLException e) {
  297. // TODO Auto-generated catch block
  298. System.out.println("error in getFriend("+id+").");
  299. }
  300. finally{close();}
  301. return li;
  302. }
  303. public Boolean addmessage(message msg){
  304. start();
  305. Boolean flag = true;
  306. try {
  307. statement.execute("insert into message(id1,id2,time,content) values('"+msg.getId1()+"','"+msg.getId2()+"','"+msg.getDate().toLocaleString()+"','"+msg.getContent()+"');");
  308. } catch (SQLException e) {
  309. // TODO Auto-generated catch block
  310. e.printStackTrace();
  311. System.out.println("error in addmessage("+msg+").");
  312. flag = false;
  313. }
  314. finally{close();}
  315. return flag;
  316. }
  317. public List<message> getfailmessage(String id){
  318. start();
  319. List<message> li=new LinkedList<message>();
  320. ResultSet re;
  321. try {
  322. re = statement.executeQuery("select * from failmessage where id2 = '"+id+"';");
  323. while(re.next()){
  324. Date date = convertToDate(re.getString(3));
  325. li.add(new message(re.getString(1),re.getString(2),date,re.getString(4)));
  326. }
  327. } catch (SQLException e) {
  328. // TODO Auto-generated catch block
  329. System.out.println("error in getfailmessage("+id+").");
  330. }
  331. finally{close();}
  332. return li;
  333. }
  334. public Boolean addfailmessage(message msg){
  335. start();
  336. Boolean flag =true;
  337. try {
  338. statement.execute("insert into failmessage(id1,id2,time,content) values('"+msg.getId1()+"','"+msg.getId2()+"','"+msg.getDate().toLocaleString()+"','"+msg.getContent()+"');");
  339. } catch (SQLException e) {
  340. // TODO Auto-generated catch block
  341. System.out.println("error in addfailmessage("+msg+").");
  342. flag = false;
  343. }
  344. finally{close();}
  345. return flag;
  346. }
  347. public Boolean deletefailmessage(message msg){//待修正--应用id确定被删除离线消息
  348. start();
  349. Boolean flag = true;
  350. try {
  351. statement.execute("delete from failmessage where id1 = '"+msg.getId1()+"'&&id2 ='"+msg.getId2()+"';");
  352. } catch (SQLException e) {
  353. // TODO Auto-generated catch block
  354. System.out.println("error in deletefailmessage("+msg+").");
  355. flag = false;
  356. }
  357. finally{close();}
  358. return flag;
  359. }
  360. public List<message> getMessage(){
  361. start();
  362. List<message> li=new LinkedList<message>();
  363. ResultSet re;
  364. try {
  365. re = statement.executeQuery("select * from message;");
  366. while(re.next()){
  367. li.add(new message(re.getString(1),re.getString(2),re.getDate(3),re.getString(4)));
  368. }
  369. } catch (SQLException e) {
  370. // TODO Auto-generated catch block
  371. System.out.println("error in getMessage().");
  372. }
  373. finally{close();}
  374. return li;
  375. }
  376. public List<message> getMessage(String id){
  377. start();
  378. List<message> li = new LinkedList<message>();
  379. try {
  380. ResultSet re = statement.executeQuery("select * from message where id1 ="+id+";");
  381. while(re.next()){
  382. String str = re.getString(3);
  383. Date date = new GregorianCalendar(new Integer(str.substring(0,4)).intValue(),new Integer(str.substring(5, 7)).intValue(),new Integer(str.substring(8, 10)).intValue(),new Integer(str.substring(11, 13)).intValue(),new Integer(str.substring(14, 16)).intValue(),new Integer(str.substring(17, 19)).intValue()).getTime();
  384. li.add(new message(re.getString(1),re.getString(2),date,re.getString(4)));
  385. }
  386. } catch (SQLException e) {
  387. // TODO Auto-generated catch block
  388. System.out.println("error in getMessage("+id+")");
  389. }
  390. return li;
  391. }
  392. public List<message> getMessage(String id1,String id2){//注意顺序,id1 查询与 id2的聊天记录。
  393. start();
  394. List<message> li=new LinkedList<message>();
  395. ResultSet re;
  396. try {
  397. re = statement.executeQuery("select * from message where (d1=1&&id1='"+id1+"'&&id2='"+id2+"')||(d2=1&&id1='"+id2+"'&&id2='"+id1+"') order by time ASC;");
  398. while(re.next()){
  399. li.add(new message(re.getString(1),re.getString(2),re.getDate(3),re.getString(4)));
  400. }
  401. } catch (SQLException e) {
  402. // TODO Auto-generated catch block
  403. e.printStackTrace();
  404. System.out.println("error in getMessage("+id1+","+id2+").");
  405. }
  406. finally{close();}
  407. return li;
  408. }
  409. public Boolean deleteMessage(String id1,String id2){
  410. start();
  411. Boolean flag = true;
  412. try {
  413. statement.execute("update message set d1 = 0 where id1 ='"+id1+"'&&id2='"+id2+"';");
  414. statement.execute("update message set d2 = 0 where id2 ='"+id1+"'&&id1='"+id2+"';");
  415. } catch (SQLException e) {
  416. // TODO Auto-generated catch block
  417. System.out.println("error in deleteMessage("+id1+","+id2+").");
  418. flag = false;
  419. }
  420. finally{close();}
  421. return flag;
  422. }
  423. public void md(){
  424. start();
  425. try{
  426. ResultSet re=statement.executeQuery("select id,pwd from user;");
  427. Vector<String> id=new Vector<String>();
  428. Vector<String> pwd=new Vector<String>();
  429. while(re.next()){
  430. id.add(re.getString(1));
  431. pwd.add(re.getString(2));
  432. }
  433. re.close();
  434. while(!id.isEmpty()){
  435. statement.execute("update user set pwd='"+encryp(pwd.remove(0))+"' where id='"+id.remove(0)+"';");
  436. }
  437. }catch(SQLException e){
  438. e.printStackTrace();
  439. }
  440. finally{
  441. close();
  442. }
  443. return;
  444. }
  445. public String encryp(String pwd){
  446. byte[] message=null;
  447. message = pwd.getBytes();
  448. MessageDigest md=null;
  449. try {
  450. md = MessageDigest.getInstance("MD5");
  451. } catch (NoSuchAlgorithmException e) {
  452. // TODO Auto-generated catch block
  453. e.printStackTrace();
  454. }
  455. byte[] encrypwd =md.digest(message);
  456. BigInteger bigInteger = new BigInteger(1, encrypwd);
  457. return bigInteger.toString(16);
  458. }
  459. }

服务器端程序Server.java

  1. package control;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.io.PrintWriter;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import java.sql.SQLException;
  10. import java.util.Date;
  11. import java.util.GregorianCalendar;
  12. import java.util.LinkedList;
  13. import java.util.List;
  14. import java.util.logging.Logger;
  15.  
  16. import model.message;
  17. import model.relation;
  18. import model.user;
  19. import dao.dao;
  20.  
  21. public class Server implements Runnable{
  22. List<user> li = new LinkedList<user>();//在线用户列表
  23. List<Socket> li_socket = new LinkedList<Socket>();
  24. ServerSocket server;
  25. Socket socket ;
  26. Object lock = new Object();
  27. Logger Log = Logger.getGlobal();
  28. public Server(int port,int queueLength){
  29. try{
  30. server = new ServerSocket(port,queueLength);//port,queueLength
  31. }catch(Exception e){}
  32. System.out.println("服务器创建成功。");
  33. }
  34.  
  35. public List<user> getLi() {
  36. return li;
  37. }
  38.  
  39. public void start(){
  40. System.out.println("服务器已启动……"+server);
  41. while(true){
  42. try{
  43. socket = server.accept();//系统在这里等待连接
  44. new Thread(this).start();
  45. System.out.println(socket.getInetAddress()+"连接服务器成功。");
  46. }catch(Exception e){
  47. System.out.println("server error");
  48. try{
  49. socket.close();
  50. }catch(Exception ee){}
  51. close();
  52. }
  53. }
  54. }
  55. //主循环,根据请求码处理用户请求
  56. public void run(){//线程处理代码段,用以监听与客户端的连接。
  57. Socket socket = this.socket;
  58. BufferedReader input;
  59. PrintWriter output;
  60. String str = "";
  61. try {
  62. input =new BufferedReader( new InputStreamReader(socket.getInputStream()));//线程在这里等待输入流
  63. output =new PrintWriter( new OutputStreamWriter(socket.getOutputStream()),true);
  64. while(true){
  65. //00:登录
  66. //10:查询与指定好友的历史消息
  67. //11:点对点发msg
  68. //12:群发好友msg
  69. //13:删除历史消息
  70. //20:获得好友列表
  71. //21:添加好友
  72. //22:删除好友
  73. //23:确认添加好友
  74. //24:拒绝好友请求
  75. //30:更新用户信息
  76. //40:注册新用户
  77. Thread.sleep(1000);
  78. try{
  79. str = input.readLine();
  80. System.out.println("服务器收到:"+str);
  81. }catch(Exception e){
  82. socket.close();
  83. System.out.println("监听断开");
  84. break;
  85. }
  86. String cmd="";
  87. if(str!=null&&str.length()>2){
  88. cmd= str.substring(0,2);
  89. }
  90. synchronized (lock) {//synchronized
  91. try{
  92. checkStatus();
  93. switch(cmd){
  94. case "00":{//处理结果:给客户端发送用户与朋友信息;登录
  95. str = str.substring(3).trim();
  96. String[] para = str.split(",");
  97. if(para.length!=2){
  98. System.out.println("参数错误。");
  99. output.println("000");
  100. break;
  101. }
  102. String id = para[0];
  103. String pwd = para[1];
  104. user u = new user(id,"*",pwd);
  105. if(login(u)){
  106. System.out.println(u+"\t 登录成功。");
  107. u = getUser(u.getId());
  108. li.add(u);
  109. li_socket.add(socket);
  110. List<user> f_li = getFriend(id);
  111. String str_f = u.getId()+","+u.getUsername()+";";
  112. for(user each:f_li){
  113. str_f = str_f + each.getId()+","+each.getUsername()+";";
  114. }
  115. List<relation> li_r = this.getFailRelation(id);
  116. String str_r ="";
  117. for(relation r:li_r){
  118. str_r = str_r +r.toString()+";";
  119. }
  120. List<message> li_m = this.getfailmessage(id);
  121. String str_m = "";
  122. for(message msg:li_m){
  123. str_m =str_m+msg.toString()+";";
  124. }
  125. str = "001:"+str_f+"&$"+str_r+"&$"+str_m;
  126. output.println(str);
  127. for(message msg:li_m){
  128. deletefailmessage(msg);
  129. }
  130. System.out.println("登录处理完成:"+str);
  131. }else{
  132. output.println("000");
  133. System.out.println(id+"\t登录失败");
  134. }
  135. };break;
  136. case "10":{//发送聊天记录序列,查询与指定好友的历史消息
  137. str = str.substring(3).trim();
  138. String para[] = str.split(",");
  139. if(para.length!=2){
  140. System.out.println("参数错误。");
  141. output.println("100");
  142. break;
  143. }
  144. String id1 = para[0];
  145. String id2 = para[1];
  146. System.out.println("10:查询与指定好友聊天记录。"+id1+","+id2);
  147. List<message> m_li = this.getMessage(id1, id2);
  148. String m_str ="";
  149. for(message msg:m_li){
  150. m_str =m_str + msg.toString()+";";
  151. }
  152. output.println("101:"+m_str);
  153. System.out.println("聊天记录查询成功:"+m_str);
  154. };break;
  155. case "11":{//点对点发msg
  156. System.out.println("点对点msg.");
  157. str = str.substring(3).trim();
  158. String[] para = str.split(",");
  159. if(para.length!=4){
  160. System.out.println("参数不匹配。");
  161. output.println("110");
  162. break;
  163. }
  164. String id1 = para[0];
  165. String id2 = para[1];
  166. System.out.println("para[2]:"+para[2]);
  167. Date date =convertToDate(para[2]);
  168. System.out.println("date:"+date);
  169. String content = para[3];
  170. message msg = new message(id1,id2,date,content);
  171. if(send(id2,"111:"+msg.toString())){
  172. System.out.println("转发成功:"+msg.toString());
  173. addmessage(msg);//发送成功后把消息存入数据库
  174. break;
  175. }else{
  176. System.out.println("目标用户未在线。");
  177. this.addfailmessage(msg);//发送不成功存入离线记录表
  178. System.out.println("转至离线消息");
  179. }
  180. };break;
  181. case "12":{//群发好友msg
  182. System.out.println("12:群发好友信息。");
  183. str = str.substring(3).trim();
  184. String[] para = str.split(",");
  185. if(para.length!=4||!para[0].equals(para[1])){
  186. System.out.println("参数不匹配。");
  187. output.println("120");
  188. break;
  189. }
  190. String id1 = para[0];
  191. String id2 = para[1];
  192. Date date = convertToDate(para[2]);
  193. String content = para[3];
  194. List<user> li_f = getFriend(id1);
  195. message msg = new message(id1,id2,date,content);
  196. for(int i=0;i<li_f.size();i++){
  197. //Boolean flag = false;
  198. id2 = li_f.get(i).getId();
  199. msg.setId2(id2);
  200. if(send(id2,"121:"+msg.toString())){
  201. addmessage(msg);
  202. System.out.println("群发消息至"+id2+"成功。");
  203. }else{
  204. addfailmessage(msg);
  205. System.out.println("转至离线消息:"+msg);
  206. }
  207. }
  208. //socket = socket_temp;
  209. output.println("121");
  210. System.out.println("群发消息处理成功。");
  211. };break;
  212. case "13":{//删除历史消息
  213. str = str.substring(3);
  214. String[] para = str.split(",");
  215. if(para.length!=2){
  216. System.out.println("参数不匹配。");
  217. output.println("130");
  218. break;
  219. }
  220. String id1 = para[0];
  221. String id2 = para[1];
  222. if(deleteMessage(id1,id2)){
  223. System.out.println("历史消息清空:"+id1+","+id2);
  224. output.println("131");
  225. }else{
  226. System.out.println("清空失败:"+id1+","+id2);
  227. output.println("130");
  228. }
  229. };break;
  230. case "20":{//获得好友列表
  231. str = str.substring(3);
  232. String[] para = str.split(",");
  233. if(para.length!=1){
  234. System.out.println("参数不匹配。");
  235. output.println("200");
  236. break;
  237. }
  238. String id = para[0];
  239. List<user> li_f = getFriend(id);
  240. String str_f = "";
  241. for(user u:li_f){
  242. str_f = str_f + u.toString()+";";
  243. }
  244. output.println("201:"+str_f);
  245. System.out.println("成功获取好友列表。");
  246. };break;
  247. case "21":{//添加好友
  248. str = str.substring(3);
  249. String[] para = str.split(",");
  250. if(para.length!=2){
  251. System.out.println("参数不匹配。");
  252. output.println("210");
  253. break;
  254. }
  255. String id1 = para[0];
  256. String id2 = para[1];
  257. //relation r = new relation((new Integer(id1).intValue()>new Integer(id2).intValue()?id2:id1),(new Integer(id1).intValue()>new Integer(id2).intValue()?id1:id2));
  258. relation r = new relation(id1,id2);
  259. addFailRelation(r);
  260. System.out.println("add temp relation:"+r);
  261. if(send(id2,"211:"+id1)){
  262. System.out.println("发出添加好友通知。");
  263. }else{
  264. System.out.println("添加好友失败。");
  265. }
  266. };break;
  267. case "22":{//删除好友
  268. str = str.substring(3);
  269. String[] para = str.split(",");
  270. if(para.length!=2){
  271. System.out.println("参数不匹配。");
  272. output.println("220");
  273. break;
  274. }
  275. String id1 = para[0];
  276. String id2 = para[1];
  277. if(new Integer(id1).intValue()>new Integer(id2).intValue()){
  278. String temp = id1;
  279. id1 = id2;
  280. id2 = temp;
  281. }
  282. relation r = new relation(id1,id2);
  283. if(deleteRelation(r)){
  284. System.out.println("删除好友关系:"+id1+","+id2+" 成功。");
  285. if(send(id2,"221:"+id1)){
  286. System.out.println("删除好友通知完成。");
  287. output.println("221:"+id2);
  288. }else{
  289. System.out.println("删除好友通知失败。");
  290. }
  291. }else{
  292. System.out.println("删除好友关系失败。");
  293. output.println("220");
  294. }
  295. };break;
  296. case "23":{//确认添加好友
  297. str = str.substring(3);
  298. String[] para = str.split(",");
  299. if(para.length!=2){
  300. System.out.println("参数不匹配。");
  301. output.println("230");
  302. break;
  303. }
  304. String id1 = para[0];
  305. String id2 = para[1];
  306. relation r = new relation(id1,id2);
  307. if(addRelation(r)){
  308. deleteFailRelation(r);
  309. System.out.println("确认添加好友关系:"+id1+","+id2+" 成功。");
  310. if(send(id2,"231:"+id1+","+getUser(id1).getUsername())){
  311. System.out.println("添加好友通知完成。");
  312. output.println("231:"+id2+","+getUser(id2).getUsername());
  313. }else{
  314. System.out.println("添加好友通知失败。");
  315. output.println("230");
  316. }
  317. }else{
  318. System.out.println("确认添加好友关系失败。");
  319. output.println("230");
  320. }
  321. };break;
  322. case "24":{//拒绝好友请求
  323. str = str.substring(3);
  324. String[] para = str.split(",");
  325. if(para.length!=2){
  326. System.out.println("参数不匹配。");
  327. output.println("240");
  328. break;
  329. }
  330. String id1 = para[0];
  331. String id2 = para[1];
  332. relation r = new relation(id1,id2);
  333. if(deleteFailRelation(r)){
  334. if(send(id2,"241:"+id1)){
  335. System.out.println("拒绝好友通知完成。");
  336. }else{
  337. System.out.println("拒绝好友通知失败。");
  338. output.println("240");
  339. }
  340. }else{
  341. System.out.println("拒绝添加好友失败。");
  342. output.println("240");
  343. }
  344. };break;
  345. case "30":{//更改用户名
  346. str = str.substring(3);
  347. String[] para = str.split(",");
  348. if(para.length!=3){
  349. System.out.println("参数不匹配。");
  350. output.println("300");
  351. break;
  352. }
  353. String id = para[0];
  354. String name = para[1];
  355. String pwd = para[2];
  356. user u = new user(id,name,pwd);
  357. if(verify(u)){
  358. System.out.println("验证成功:"+u);
  359. if(updateUser(u)){
  360. System.out.println("用户信息更新成功。");
  361. output.println("301:"+u.toString());
  362. }else{
  363. System.out.println("用户信息更新失败。");
  364. output.println("300");
  365. }
  366. }else{
  367. System.out.println("验证失败。");
  368. output.println("300");
  369. }
  370. };break;
  371. case "31":{//更改用户密码
  372. str = str.substring(3);
  373. String[] para = str.split(",");
  374. if(para.length!=3){
  375. System.out.println("参数不匹配。");
  376. output.println("310");
  377. break;
  378. }
  379. String id = para[0];
  380. String name = para[1];
  381. String pwd = para[2];
  382. user u = new user(id,name,pwd);
  383. if(verify(u)){
  384. System.out.println("验证成功:"+u);
  385. if(updatePwd(u)){
  386. System.out.println("用户信息更新成功。");
  387. u = getUser(id);
  388. output.println("301:"+u.toString());
  389. }else{
  390. System.out.println("用户信息更新失败。");
  391. output.println("300");
  392. }
  393. }else{
  394. System.out.println("验证失败。");
  395. output.println("300");
  396. }
  397. };break;
  398. case "40":{//注册新用户
  399. str = str.substring(3);
  400. String[] para = str.split(",");
  401. if(para.length!=2){
  402. System.out.println("参数不匹配。");
  403. output.println("400");
  404. break;
  405. }
  406. String name = para[0];
  407. String pwd = para[1];
  408. user u = new user("*",name,pwd);
  409. if(register(u)){
  410. u = getUser(name,pwd);
  411. System.out.println("用户注册成功。");
  412. output.println("401:"+u.toString());
  413. }else{
  414. System.out.println("用户注册失败");
  415. output.println("400");
  416. }
  417. };break;
  418. case "55":output.println("echo\t"+str.substring(2));break;
  419. default:{
  420. System.out.println("请求码匹配失败。");
  421. output.println("-1");
  422. };break;
  423. }
  424. }catch(Exception e){
  425. e.printStackTrace();
  426. }
  427. }//synchronized
  428. }
  429. }catch(Exception e){
  430. try{
  431. socket.close();
  432. System.out.println("服务器出现异常。");
  433. e.printStackTrace();
  434. }catch(Exception ee){}
  435. }
  436. }
  437. private void checkStatus(){//需要注意删除
  438. for(int i=0;i<li_socket.size();i++){
  439. System.out.println("检查第"+i+"个连接的状态。");
  440. if(!li_socket.get(i).isBound()){
  441. li.remove(i);
  442. li_socket.remove(i);
  443. System.out.println("清除第"+i+"个连接。");
  444. i--;
  445. }
  446. }
  447. System.out.println("状态扫描完成。");
  448. }
  449. private static Date convertToDate(String str){//用于将sql.date转化为util.date
  450. String[] li = str.split(" ");
  451. if(li.length!=2){
  452. System.out.println("converToDate 出错,空格错误");
  453. return new Date();
  454. }
  455. String[] para = li[0].split("-");
  456. String[] para1 = li[1].split(":");
  457. return new GregorianCalendar(new Integer(para[0]).intValue(),new Integer(para[1]).intValue(),new Integer(para[2]).intValue(),new Integer(para1[0]).intValue(),new Integer(para1[1]).intValue(),new Integer(para[2]).intValue()).getTime();
  458. }
  459. private Boolean send(String id,String str){
  460. System.out.println("开始转发");
  461. Boolean flag = false;
  462. for(int i=0;i<li.size();i++)
  463. {
  464. if(id.equals(li.get(i).getId())){
  465. Socket socket = li_socket.get(i);
  466. PrintWriter output;
  467. try {
  468. output = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()),true);
  469. output.println(str);
  470. output.flush();
  471. System.out.println("转发完成");
  472. flag =true;
  473. } catch (IOException e) {
  474. // TODO Auto-generated catch block
  475. flag = false;
  476. System.out.println("error in send"+i+","+str);
  477. }
  478. }
  479. }
  480. return flag;
  481. }
  482. private String receive(){
  483. String str ="";
  484. BufferedReader input =null;
  485. try{
  486. input =new BufferedReader( new InputStreamReader(socket.getInputStream()));//线程在这里等待输入流
  487. while(str.equals("")){
  488. str = input.readLine();
  489. }
  490. }catch(Exception e){
  491. System.out.println("socket 接收出错。");
  492. }finally{
  493. try {
  494. input.close();
  495. } catch (IOException e) {
  496. // TODO Auto-generated catch block
  497. e.printStackTrace();
  498. }
  499. }
  500. return str;
  501. }
  502. private List<user> getUserList(){
  503. return new dao().getUserList();
  504. }
  505. private Boolean register(user u){
  506. user u_temp = new dao().getUser(u.getUsername(), u.getPwd());
  507. Boolean flag = false;
  508. if(u_temp==null){
  509. new dao().addUser(u);
  510. flag = true;
  511. }else{
  512. flag = false;
  513. }
  514. return flag;
  515. }
  516. private Boolean login(user u){
  517. if(verify(u)){
  518. return true;
  519. }else{
  520. return false;
  521. }
  522. }
  523. private Boolean verify(user u){
  524. user du = getUser(u.getId());
  525. return du.getPwd().equals(u.getPwd());
  526. }
  527. private user getUser(String id){
  528. return new dao().getUser(id);
  529. }
  530. private user getUser(String name,String pwd){
  531. return new dao().getUser(name,pwd);
  532. }
  533. private Boolean deleteUser(String id){
  534. return new dao().deleteUser(id);
  535. }
  536. private Boolean updateUser(user u){
  537. return new dao().updateUser(u);
  538. }
  539. private Boolean updatePwd(user u){
  540. return new dao().updatePwd(u);
  541. }
  542. private List<relation> getRelation(){
  543. return new dao().getRelation();
  544. }
  545. private Boolean addRelation(relation r){
  546. return new dao().addRelation(r);
  547. }
  548. private Boolean deleteRelation(relation r){
  549. return new dao().deleteRelation(r);
  550. }
  551. private List<relation> getFailRelation(String id){
  552. return new dao().getFailRelation(id);
  553. }
  554. private Boolean addFailRelation(relation r){
  555. return new dao().addFailRelation(r);
  556. }
  557. private Boolean deleteFailRelation(relation r){
  558. return new dao().deleteFailRelation(r);
  559. }
  560. private List<user> getFriend(String id){
  561. return new dao().getFriend(id);
  562. }
  563. private Boolean addmessage(message msg){
  564. return new dao().addmessage(msg);
  565. }
  566. private List<message> getfailmessage(String id){
  567. return new dao().getfailmessage(id);
  568. }
  569. private Boolean addfailmessage(message msg){
  570. return new dao().addfailmessage(msg);
  571. }
  572. private Boolean deletefailmessage(message msg){
  573. return new dao().deletefailmessage(msg);
  574. }
  575. private List<message> getMessage(String id)//指定用户聊天记录
  576. {
  577. return new dao().getMessage(id);
  578. }
  579. private List<message> getMessage(String id1,String id2)//特定的两人的聊天记录
  580. {
  581. return new dao().getMessage(id1, id2);
  582. }
  583. private List<message> getMessage()//所有聊天记录
  584. {
  585. return new dao().getMessage();
  586. }
  587. private Boolean deleteMessage(String id1,String id2){
  588. return new dao().deleteMessage(id1, id2);
  589. }
  590. public void close()//关闭服务器;
  591. {
  592. try {
  593. server.close();
  594. System.out.println("服务器已关闭");
  595. } catch (IOException e) {
  596. // TODO Auto-generated catch block
  597. System.out.println("服务器关闭出错。");
  598. }
  599. }
  600. }

服务器界面ServerView.java:

package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder; import model.user;
import control.Server; public class ServerView extends JFrame implements Runnable{ private Server server;
private JPanel contentPane;
private JTextArea textArea;
private JTextArea textArea_1;
private ByteArrayOutputStream baos;
private PrintStream old; /**
* Launch the application.
*/
public static void main(String[] args) {
try {
ServerView frame = new ServerView();
frame.setVisible(true);
frame.start();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* Create the frame.
*/
public ServerView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Show what happened
System.out.println("Here: " + baos.toString()); setBounds(100, 100, 514, 305);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null); JButton btnNewButton = new JButton("关闭服务器");
ServerView ser = this;
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnNewButton.setBounds(351, 232, 137, 23);
contentPane.add(btnNewButton); JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(23, 20, 343, 202);
contentPane.add(scrollPane); textArea = new JTextArea();
scrollPane.setViewportView(textArea); JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(376, 20, 112, 202);
contentPane.add(scrollPane_1); textArea_1 = new JTextArea();
scrollPane_1.setViewportView(textArea_1); JLabel lblNewLabel = new JLabel("服务器日志:");
lblNewLabel.setBounds(23, 0, 103, 15);
contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("在线用户:");
lblNewLabel_1.setBounds(376, 0, 112, 15);
contentPane.add(lblNewLabel_1); }
public void start(){
new Thread(this).start();
try{
server = new Server(2002,4000);
server.start();
}catch(Exception ee){}
finally{
server.close();
System.setOut(old);
System.out.println("done");
}
}
@Override
public void run() {
// TODO Auto-generated method stub
String str="";
String str1="";
while(true){
System.out.flush();
str = baos.toString();
textArea.setText(str);
str1="";
if(server!=null){
List<user> li = server.getLi();
for(int i=0;i<li.size();i++){
user u= li.get(i);
str1 += u.getId()+" "+u.getUsername()+"\n";
}
}
textArea_1.setText(str1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("error in ServerView sleep(500)");
}
}
}
}

客户端代码Client.java:

package control;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger; import model.message;
import model.relation;
import model.user;
public class Client implements Runnable{
Socket socket;
user client;
List<user> li_friend = new LinkedList<user>();
List<relation> li_relation = new LinkedList<relation>();
List<message> li_offlineMsg = new LinkedList<message>();
List<message> li_historyMsg = new LinkedList<message>();
BufferedReader input ;
PrintWriter output;
Logger Log = Logger.getGlobal();
public Client(){
try{
socket = new Socket("127.0.0.1", 2002);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
}catch(Exception e){
try{
input.close();
output.close();
socket.close();
}catch(Exception ee){}
//System.out.println("创建客户端出现异常。");
}
//System.out.println("创建客户端……");
}
public void start(){
new Thread(this).start();
Scanner sc = new Scanner(System.in);
String cmd="";
while(true){
//System.out.print(">>>");
cmd = sc.nextLine();
switch(cmd){
case "quit":System.exit(0);break;
}
send(cmd);
}
}
private void send(String str){
output.println(str);
output.flush();
}
public void run(){//用于监听服务器
String str = "";
//System.out.println("开始监听服务器……");
try{
while(true){
Thread.sleep(1000);
str = input.readLine();
//System.out.println("接收到:"+str);
if(str.length()>0){
//System.out.print(">>>");
}
try{
String cmd = str.substring(0,3);
String old_str = str;
if(str.length()>4){
str = str.substring(4);
}
switch(cmd){
case "001"://System.out.println("登录成功");
{
String[] li = str.split("&");
String[] u_str = li[0].split(";");
String[] para = u_str[0].split(",");
client = new user(para[0],para[1]);
for(int i=1;i<u_str.length;i++){
para = u_str[i].split(",");
if(para.length==2){
li_friend.add(new user(para[0],para[1]));
}
}
if(li[1]!=null&&li[1].length()>1){
li[1] = li[1].substring(1);
String[] r_str = li[1].split(";");
for(int i=0;i<r_str.length;i++){
para = r_str[i].split(",");
li_relation.add(new relation(para[0],para[1]));
}
}
if(li[2]!=null&&li[2].length()>1){
li[2]=li[2].substring(1);
String[] m_str = li[2].split(";");
for(int i = 0;i<m_str.length;i++){
para = m_str[i].split(",");
li_offlineMsg.add(new message(para[0],para[1],convertToDate(para[2]),para[3]));//convertToDate(str);
}
}
for(user u:li_friend){
//System.out.println(u);
}
//System.out.println("001解析完成。");
}break;
case "101"://System.out.println("查询与指定好友的历史消息成功");
{
String[] m_str = str.split(";");
for(int i=0;i<m_str.length;i++){
String[] para = m_str[i].split(",");
li_historyMsg.add(new message(para[0],para[1],convertToDate(para[2]),para[3]));
}
}break;
case "111"://System.out.println("点对点接收msg");
{
//System.out.println("111:"+str);
String para[] = str.split(",");
if(para.length==4){
message msg = new message(para[0],para[1],convertToDate(para[2]),para[3]);
li_offlineMsg.add(msg);
//System.out.println("消息链中加入消息:"+msg.toString());
}
}break;
case "121"://System.out.println("群发好友msg成功");
{
//System.out.println("121:"+str);
String para[] = str.split(",");
if(para.length==4){
message msg = new message(para[0],para[1],convertToDate(para[2]),para[3]);
li_offlineMsg.add(msg);
//System.out.println("消息链中加入消息:"+msg.toString());
}
}break;
case "131"://System.out.println("删除历史消息成功");
break;
case "201"://System.out.println("获得好友列表成功");
{
String[] u_str = str.split(";");
for(int i=0;i<u_str.length;i++){
String[] para = u_str[i].split(",");
if(para.length==2){
li_friend.add(new user(para[0],para[1]));
}
}
}break;
case "211"://System.out.println("添加好友成功");
{
String para[] =str.split(",");
if(para.length==1){
li_relation.add(new relation(para[0],client.getId()));
//System.out.println("收到"+para[0]+"的好友请求。");
}
}break;
case "221"://System.out.println("删除好友成功");
break;
case "231"://System.out.println("确认添加好友成功");
{
String para[] = str.split(",");
if(para.length==2){
//li_friend.add(new user(para[0],para[1]));
}
}break;
case "241"://System.out.println("拒绝添加好友");
{ }break;
case "301"://System.out.println("更新用户信息成功");
break;
case "401"://System.out.println("注册新用户成功");
{
String para[] = str.split(",");
if(para.length==3){
client = new user(para[0],para[1],para[2]);
}
}break;
//失败
case "000"://System.out.println("登录失败");
break;
case "100"://System.out.println("查询与指定好友的历史消息失败");
break;
case "110"://System.out.println("点对点发msg失败");
break;
case "120"://System.out.println("群发好友msg失败");
break;
case "130"://System.out.println("删除历史消息失败");
break;
case "200"://System.out.println("获得好友列表失败");
break;
case "210"://System.out.println("添加好友失败");
break;
case "220"://System.out.println("删除好友失败");
break;
case "230"://System.out.println("确认添加好友失败");
break;
case "300"://System.out.println("更新用户信息失败");
break;
case "400"://System.out.println("注册新用户失败");
{
client = new user("-1","-1");
}break;
default: //System.out.print("遇到未识别的返回码:"+old_str);
break;
}
}catch(Exception e){
//System.out.println("解析服务器返回结果出错。");
e.printStackTrace();
}
}
}catch(Exception e){}
}
private static Date convertToDate(String str){//用于将sql.date转化为util.date
String[] li = str.split(" ");
if(li.length!=2){
//System.out.println("converToDate 出错,空格错误");
return new Date();
}
String[] para = li[0].split("-");
String[] para1 = li[1].split(":");
return new GregorianCalendar(new Integer(para[0]).intValue(),new Integer(para[1]).intValue(),new Integer(para[2]).intValue(),new Integer(para1[0]).intValue(),new Integer(para1[1]).intValue(),new Integer(para[2]).intValue()).getTime();
}
public Boolean login(String id,String pwd){//00:登录
String str = "00:"+id+","+pwd;
output.println(str);
output.flush();
return true;
}
public Boolean getMessage(String id)//10:查询与指定好友的历史消息
{
String str = "10:"+client.getId()+","+id;
output.println(str);
output.flush();
return true;
}
public Boolean send(String id,String content)//11:点对点发msg
{
String str = "11:"+client.getId()+","+id+","+new Date().toLocaleString()+","+content;
output.println(str);
output.flush();
return true;
}
public Boolean sendAll(String content)//12:群发好友msg
{
String str = "12:"+client.getId()+","+client.getId()+","+new Date().toLocaleString()+","+content;
output.println(str);
output.flush();
return true;
}
public Boolean deleteMessage(String id)//13:删除历史消息
{
String str = "13:"+client.getId()+","+id;
output.println(str);
output.flush();
return true;
}
public Boolean getFriend()//20:获得好友列表
{
li_friend=new LinkedList<user>();//获取好友列表列表申请发出后,好友列表清空。
String str = "20:"+client.getId();
output.println(str);
output.flush();
return true;
}
public Boolean addRelation(String id)//21:添加好友
{
String str = "21:"+client.getId()+","+id;
output.println(str);
output.flush();
return true;
}
public Boolean deleteRelation(String id)//22:删除好友
{
String str = "22:"+new relation(client.getId(),id).toString();
output.println(str);
return true;
}
public Boolean confirmRelation(String id)//23:确认添加好友
{
String str = "23:"+client.getId()+","+id;
output.println(str);
output.flush();
for(relation r:li_relation){
if(r.getId1().equals(id)||r.getId2().equals(id)){
li_relation.remove(r);
}
}
return true;
}
public Boolean refuseRelation(String id)//24:拒绝好友请求
{
String str = "24:"+client.getId()+","+id;
output.println(str);
output.flush();
for(relation r:li_relation){
if(r.getId1().equals(id)||r.getId2().equals(id)){
li_relation.remove(r);
}
}
return true;
}
public Boolean updateInfo(String name,String pwd)//30:更改用户名
{
String str = "30:"+new user(client.getId(),name,pwd).toString();
output.println(str);
return true;
}
public Boolean updatePwd(String newpwd,String oldpwd)//31:更改用户密码
{
String str = "30:"+new user(client.getId(),newpwd,oldpwd).toString();
output.println(str);
return true;
}
public Boolean register(String name,String pwd)//40:注册新用户
{
String str = "40:"+new user(name,pwd).toString();
output.println(str);
return true;
} public List<user> getLi_friend() {
return li_friend;
}
public void setLi_friend(List<user> li_friend) {
this.li_friend = li_friend;
}
public List<relation> getLi_relation() {
return li_relation;
}
public void setLi_relation(List<relation> li_relation) {
this.li_relation = li_relation;
}
public List<message> getLi_offlineMsg() {
return li_offlineMsg;
}
public void setLi_offlineMsg(List<message> li_offlineMsg) {
this.li_offlineMsg = li_offlineMsg;
}
public List<message> getLi_historyMsg() {
return li_historyMsg;
}
public void setLi_historyMsg(List<message> li_historyMsg) {
this.li_historyMsg = li_historyMsg;
} public user getClient() {
return client;
}
public void logout(){
client=null;
}
public void close(){
try {
PrintWriter p = new PrintWriter("off_msg.txt");
for(message msg:li_offlineMsg){
p.println(msg.toString());
}
p.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
//System.out.println("离线消息丢失");
}
try{
input.close();
output.close();
socket.close();
}catch(Exception e){
//System.out.println("客户端退出时出现异常。");
}
//System.out.println("客户端已退出。");
}
}

登录界面loginview.java:

package view;

import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField; import control.Client; public class loginview extends JFrame implements Runnable {
private Client client;
private JTextField textField;
private JPasswordField passwordField;
private JLabel lblNewLabel_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
loginview frame = new loginview(new Client());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public loginview(Client client) {
this.client = client;
Toolkit tool = getToolkit();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("用户名:");
lblNewLabel.setBounds(79, 83, 81, 30);
getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("密码:");
lblNewLabel_1.setBounds(79, 127, 81, 30);
getContentPane().add(lblNewLabel_1); textField = new JTextField();
textField.setBounds(170, 88, 165, 21);
getContentPane().add(textField);
textField.setColumns(10); passwordField = new JPasswordField();
passwordField.setBounds(170, 132, 165, 21);
getContentPane().add(passwordField); JButton btnNewButton = new JButton("登录");
loginview lv = this;
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(lv).start();
}
});
btnNewButton.setBounds(79, 188, 93, 23);
getContentPane().add(btnNewButton); JButton btnNewButton_1 = new JButton("注册");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
new registerview(client).setVisible(true);;
}
});
btnNewButton_1.setBounds(182, 188, 93, 23);
getContentPane().add(btnNewButton_1); JButton btnNewButton_2 = new JButton("取消");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnNewButton_2.setBounds(285, 188, 93, 23);
getContentPane().add(btnNewButton_2); lblNewLabel_2 = new JLabel("");
lblNewLabel_2.setBounds(122, 24, 256, 33);
getContentPane().add(lblNewLabel_2);
setResizable(false);
}
public String encryp(String pwd){
byte[] message=null;
message = pwd.getBytes();
MessageDigest md=null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encrypwd =md.digest(message);
BigInteger bigInteger = new BigInteger(1, encrypwd);
return bigInteger.toString(16);
}
public void run(){
char[] ch = passwordField.getPassword();
String pwd = "";
for(int i=0;i<ch.length;i++){
pwd +=ch[i];
ch[i]=' ';
}
client.login(textField.getText(),encryp(pwd));
int time =0;
lblNewLabel_2.setText("正在登录……");
while(client.getClient()==null&&time<100){
time++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//System.out.println("延时");
}
}
if(time==100){
lblNewLabel_2.setText("登录超时,请使用正确的用户名与密码");
}else{
setVisible(false);
ClientView clientview = new ClientView(client);
clientview.setVisible(true);
new Thread(clientview).start();
}
}
}

注册界面registerview.java:

package view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder; import model.user;
import control.Client; public class registerview extends JDialog implements Runnable{ private Client client;
private final JPanel contentPanel = new JPanel();
private JTextField textField;
private JPasswordField passwordField;
private JPasswordField passwordField_1;
private JLabel lblNewLabel; /**
* Launch the application.
*/
public static void main(String[] args) {
try {
registerview dialog = new registerview(new Client());
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
} /**
* Create the dialog.
*/
public registerview(Client client){
this.client = client;
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null); JLabel label = new JLabel("\u7528\u6237\u540D\uFF1A"); label.setBounds(118, 39, 73, 28);
contentPanel.add(label); JLabel label_1 = new JLabel("\u5BC6\u7801\uFF1A");
label_1.setBounds(128, 77, 54, 26);
contentPanel.add(label_1); JLabel label_2 = new JLabel("\u91CD\u65B0\u8F93\u5165\u5BC6\u7801\uFF1A");
label_2.setBounds(97, 113, 116, 31);
contentPanel.add(label_2); textField = new JTextField();
textField.setBounds(190, 39, 150, 28);
contentPanel.add(textField);
textField.setColumns(10); passwordField = new JPasswordField();
passwordField.setBounds(190, 77, 150, 26);
contentPanel.add(passwordField); passwordField_1 = new JPasswordField();
passwordField_1.setBounds(191, 116, 150, 25); registerview review = this; contentPanel.add(passwordField_1); lblNewLabel = new JLabel("");
lblNewLabel.setBounds(145, 174, 183, 28);
contentPanel.add(lblNewLabel);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
char [] pwd = passwordField.getPassword();
char [] pwd1 = passwordField_1.getPassword();
Boolean flag = true;
if(pwd.length!=pwd1.length){
flag =false;
}
String str = "";
for(int i=0;flag&&i<pwd.length;i++){
if(pwd[i]!=pwd1[i]){
flag =false;
}
str +=pwd[i];
pwd[i]=' ';
pwd1[i]=' ';
}
if(flag){
client.register(textField.getText(), encryp(str));
new Thread(review).start();
}else{
JOptionPane.showMessageDialog(null, "两次密码不一致", "请重新输入", JOptionPane.ERROR_MESSAGE);
}
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setResizable(false);
}
public String encryp(String pwd){
byte[] message=null;
message = pwd.getBytes();
MessageDigest md=null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] encrypwd =md.digest(message);
BigInteger bigInteger = new BigInteger(1, encrypwd);
return bigInteger.toString(16);
}
public void run(){
user u = client.getClient();
lblNewLabel.setText("系统正在处理……");
while(u==null){
u=client.getClient();
//System.out.println(u);
}
Icon icon =new ImageIcon("1.png");
if(u.getUsername().equals("-1")){
JOptionPane.showConfirmDialog(null, "该用户名已被占用"+":\n请重新输入用户名", "注册失败", JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE,icon);
}else{
JOptionPane.showConfirmDialog(null, u.getUsername()+":\n你的账号是:"+u.getId(), "注册成功", JOptionPane.CLOSED_OPTION, JOptionPane.WARNING_MESSAGE,icon);
}
textField.setText("");
passwordField.setText("");
passwordField_1.setText("");
client.logout();
lblNewLabel.setText("系统处理成功");
}
}

客户端主界面ClientView.java:

package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder; import model.message;
import model.user;
import control.Client; public class ClientView extends JFrame implements Runnable{ private Client client;
private List<Chat> li_chat=new LinkedList<Chat>();
private JPanel contentPane;
private Object lock = new Object();
private List<JPanel> li_panel_1=new LinkedList<JPanel>();
private List<JButton> li_btnNewButton=new LinkedList<JButton>();
private List<JLabel> li_JlblNewLabel_2=new LinkedList<JLabel>();
private List<user> li_u=new LinkedList<user>();
private JButton button_2;
private JPanel panel;
/*
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ClientView frame = new ClientView(new Client());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public ClientView(Client client) {
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 280, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//System.out.println(client.getClient());
JLabel lblNewLabel = new JLabel(client.getClient().toString());
contentPane.add(lblNewLabel, BorderLayout.NORTH); JToolBar toolBar = new JToolBar();
contentPane.add(toolBar, BorderLayout.SOUTH); JButton button = new JButton("\u7FA4\u53D1\u6D88\u606F");
button.addActionListener(new ActionListener() {//群发消息
public void actionPerformed(ActionEvent e) {
new GChat(client).setVisible(true);
}
});
toolBar.add(button); JButton button_1 = new JButton("\u6DFB\u52A0\u597D\u53CB");
button_1.addActionListener(new ActionListener() {//添加好友
public void actionPerformed(ActionEvent e) {
new addfriend(client).setVisible(true);
}
});
toolBar.add(button_1); button_2 = new JButton("\u597D\u53CB\u8BF7\u6C42");
button_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {//处理好友请求
new ConformFriend(client).setVisible(true);
}
});
toolBar.add(button_2);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER); JLabel lblNewLabel_1 = new JLabel("好友列表:");
scrollPane.setColumnHeaderView(lblNewLabel_1); panel = new JPanel();
scrollPane.setViewportView(panel);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); li_u = client.getLi_friend();
panel.setLayout(new GridLayout(li_u.size()+10, 1, 0, 0));
for(int i=0;i<li_u.size();i++){
li_chat.add(null);
}
for(int i=0;i<li_u.size();i++){
user u= li_u.get(i);
JPanel panel_1 = new JPanel();
li_panel_1.add(panel_1);
panel.add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("chat");
li_btnNewButton.add(btnNewButton);
btnNewButton.setName(""+i);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(lock){
JButton button = (JButton) e.getSource();
int num = new Integer(button.getName()).intValue();
Chat chat = li_chat.get(num);
if(true){
chat=new Chat(client,li_u.get(num));
li_chat.set(num, chat);
chat.setVisible(true);
chat.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
li_btnNewButton.get(num).setBackground(new Color(100,100,100));
}
}
}
}); panel_1.add(btnNewButton, BorderLayout.EAST); JLabel JlblNewLabel_2 = new JLabel(u.getId()+" "+u.getUsername());
li_JlblNewLabel_2.add(JlblNewLabel_2);
panel_1.add(JlblNewLabel_2, BorderLayout.CENTER);
}
} @Override
public void run() {
// TODO Auto-generated method stub
while(true){
List<user> li_curuser=new LinkedList<user>();
client.getFriend();//先用一个新的好友链替代原有链,再等待接收数据
while(li_curuser.size()==0){
li_curuser=client.getLi_friend();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//System.out.println("error in getli_friend");
}
}
//System.out.println();
//System.out.print("li_u:");
for(int i=0;i<li_u.size();i++){
//System.out.print(li_u.get(i)+";");
}
//System.out.println();
//System.out.print("li_curuser:");
for(int i=0;i<li_curuser.size();i++){
user user_cur = li_curuser.get(i);
Boolean flag =false;//包含为真,不包含为假
for(int j=0;j<li_u.size();j++){
if(li_u.get(j).getId().equals(user_cur.getId())){
flag=true;
break;
}
}
if(!flag){//不包含则添加
int index = li_u.size();
li_u.add(user_cur);
li_chat.add(null);
JPanel panel_1 = new JPanel();
li_panel_1.add(panel_1);
panel.add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("chat");
li_btnNewButton.add(btnNewButton);
btnNewButton.setName(""+index);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchronized(lock){
JButton button = (JButton) e.getSource();
int num = new Integer(button.getName()).intValue();
Chat chat = li_chat.get(num);
if(chat==null||true){
chat=new Chat(client,li_u.get(num));
li_chat.set(num,chat);
chat.setVisible(true);
chat.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
li_btnNewButton.get(num).setBackground(new Color(100,100,100));
}
}
}
});
panel_1.add(btnNewButton, BorderLayout.EAST);
JLabel JlblNewLabel_2 = new JLabel(user_cur.getId()+" "+user_cur.getUsername());
li_JlblNewLabel_2.add(JlblNewLabel_2);
panel_1.add(JlblNewLabel_2, BorderLayout.CENTER);
//System.out.println("add"+i);
}
}
revalidate();
repaint();
for(int i=0;i<li_u.size();i++){
user user_cur = li_u.get(i);
Boolean flag =false;
for(int j=0;j<li_curuser.size();j++){
if(li_curuser.get(j).getId().equals(user_cur.getId())){
flag=true;
break;
}
}
if(!flag){
//System.out.println("remove"+i);
li_curuser.remove(i);
li_u.remove(i);
li_chat.remove(i);
li_panel_1.remove(i);
i--;
}
}
revalidate();
repaint();
List<message> li_m = client.getLi_offlineMsg();
Set<String> set_m = new HashSet<String>();
for(message msg:li_m){
set_m.add(msg.getId1());
}
for(int i=0;i<li_u.size();i++){
if(set_m.contains(li_u.get(i).getId())){
li_btnNewButton.get(i).setBackground(new Color(255,100,100));
}else{
li_btnNewButton.get(i).setBackground(new Color(0x6495ED));
} }
if(client.getLi_relation().size()>0){
button_2.setEnabled(true);
}else{
button_2.setEnabled(false);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
//System.out.println("error in run sleep(500)");
}
} } }

好友聊天界面:Chat.java

package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder; import model.message;
import model.user;
import control.Client;
import javax.swing.JScrollPane; public class Chat extends JFrame implements Runnable{ private Client client;
private user USER;
private String msg="";
private JTextArea textArea;
private JTextArea textArea_1;
private JPanel contentPane;
private JScrollPane scrollPane;
private JScrollPane scrollPane_1; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Chat frame = new Chat(new Client(),new user("120","Yozane"));
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public Chat(Client client,user u) {
this.client = client;
this.USER = u;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null); scrollPane = new JScrollPane();
scrollPane.setBounds(5, 197, 424, 59);
contentPane.add(scrollPane); JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(new BorderLayout(0, 0)); textArea = new JTextArea();
panel.add(textArea); JButton btnNewButton = new JButton("发送");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!textArea.getText().equals("")){
client.send(USER.getId(),textArea.getText());
msg += client.getClient().getUsername()+":\n "+textArea.getText()+"\n";
textArea.setText("");
textArea_1.setText(msg);
}
}
});
panel.add(btnNewButton, BorderLayout.EAST); scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(5, 20, 424, 177);
contentPane.add(scrollPane_1); textArea_1 = new JTextArea();
scrollPane_1.setViewportView(textArea_1);
textArea_1.setEditable(false);
textArea_1.setBackground(new Color(0xB9D3EE)); JLabel lblNewLabel = new JLabel(USER.getUsername());
lblNewLabel.setBounds(5, 5, 424, 15);
contentPane.add(lblNewLabel);
Thread p = new Thread(this);
p.start();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
p.stop();
}
});
setResizable(false);
}
public String getMsg() {
return msg;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
List<message> li = client.getLi_offlineMsg();
for(message m:li){
if(m.getId1().equals(USER.getId())){
msg = msg+ USER.getUsername()+":"+m.getDate().toLocaleString()+"\n "+m.getContent()+"\n";
textArea_1.setText(msg);
li.remove(m);
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

群发消息界面GChat.java

package view;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder; import model.user;
import control.Client; public class GChat extends JFrame { private Client client;
private JPanel contentPane; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GChat frame = new GChat(new Client());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public GChat(Client client) {
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0)); JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
panel.setLayout(new BorderLayout(0, 0)); JTextArea textArea = new JTextArea();
panel.add(textArea); JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER); JTextArea textArea_1 = new JTextArea();
scrollPane.setViewportView(textArea_1); JButton btnNewButton = new JButton("群发");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = textArea_1.getText();
user USER = client.getClient();
client.sendAll(textArea.getText());
str += client.getClient().getUsername()+":\n "+textArea.getText()+"\n";
textArea.setText("");
textArea_1.setText(str);
}
});
panel.add(btnNewButton, BorderLayout.EAST);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
} }

添加好友页面addfriend.java

package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder; import model.user;
import control.Client; public class addfriend extends JFrame { private Client client;
private JPanel contentPane;
private JTextField textField; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
addfriend frame = new addfriend(new Client());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public addfriend(Client client) {
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 361, 221);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null); textField = new JTextField();
textField.setBounds(87, 53, 145, 40);
contentPane.add(textField);
textField.setColumns(10); JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(87, 116, 254, 38);
contentPane.add(lblNewLabel_1); JButton btnNewButton = new JButton("发送");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String id = ""+textField.getText();
if(client.getClient().getId().equals(id)||id.equals("")){
if(id.equals("")){
lblNewLabel_1.setText("请输入对方账号");
}else{
lblNewLabel_1.setText("请不要输入自己的账号");
textField.setText("");
}
}else{
List<user> li = client.getLi_friend();
Boolean flag =true;
for(user u:li){
if(u.getId().equals(id)){
flag =false;
break;
}
}
if(flag){
//System.out.println("addfriend("+id+")");
client.addRelation(id);
lblNewLabel_1.setText("已给"+id+"发送好友请求,等待对方确认");
textField.setText("");
}else{
lblNewLabel_1.setText(id+"已经是你的好友了");
textField.setText("");
}
}
}
});
btnNewButton.setBounds(242, 53, 93, 40);
contentPane.add(btnNewButton); JLabel lblNewLabel = new JLabel("对方账号:");
lblNewLabel.setBounds(10, 52, 80, 40);
contentPane.add(lblNewLabel); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}

确认添加好友ConformFriend.java

package view;

import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List; import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder; import model.relation;
import control.Client; public class ConformFriend extends JFrame { private Client client;
private JPanel contentPane; /**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConformFriend frame = new ConformFriend(new Client());
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} /**
* Create the frame.
*/
public ConformFriend(Client client) {
this.client = client;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 389, 208);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(5, 1, 0, 0));
List<relation> li = client.getLi_relation();
for(int i=0;i<li.size();i++){
relation r = li.get(i);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1);
panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel lblNewLabel = new JLabel(r.getId1()+"\t\t请求添加你为好友");
panel_1.add(lblNewLabel); JButton btnNewButton = new JButton("同意");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if(r.getId1()==null){
button.setEnabled(false);
}else{
client.confirmRelation(r.getId1());
Icon icon = new ImageIcon("receive.jpg");
JOptionPane.showMessageDialog(null,"你已同意添加"+r.getId1()+"为好友","添加好友", JOptionPane.OK_OPTION,icon);
button.setText("已同意");
button.setEnabled(false);
r.setId1(null);
}
}
});
panel_1.add(btnNewButton); JButton btnNewButton_1 = new JButton("拒绝");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if(r.getId1()==null){
button.setEnabled(false);
}else{
client.refuseRelation(r.getId1());
Icon icon = new ImageIcon("refuse.jpg");
JOptionPane.showMessageDialog(null,"你拒绝了"+r.getId1()+"的好友申请","拒绝好友",JOptionPane.OK_OPTION,icon);
button.setText("已拒绝");
button.setEnabled(false);
r.setId1(null);
}
}
});
panel_1.add(btnNewButton_1); }
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
} }

代码中核心部分在于Server.java、Client.java、ClientView.java.

该项目代码存放在:https://github.com/OOMMYY/ICQ

ICQ的更多相关文章

  1. 用ASP.Net写一个发送ICQ信息的程序

    用ASP.Net写一个发送ICQ信息的程序 这里我给大家提供一个很实用的例子,就是在线发送ICQ信息.想一想我们在网页上直接给朋友发送ICQ信息,那是多么美妙的事情啊.呵呵,在吹牛啊,其实ICQ本来就 ...

  2. 几款web版整合(QQ、msn、icq、yahoo通、Gtalk等)即时聊天http://hi.baidu.com/ejie/blog/item/e89794ef9a9431efce1b3ebd.html

        直到近期为止,我们经常使用的即时聊天工具(QQ.msn等)了Web版,大家不用下载庞大软件,直接打开网页就能够与自己的好友聊天,很方便.在此将时汇总,便于大家查找,节约大家一点时间. 此都是官 ...

  3. java web学习总结(二十七) -------------------JSP标签介绍

    一.JSP标签介绍 JSP标签也称之为Jsp Action(JSP动作)元素,它用于在Jsp页面中提供业务逻辑功能,避免在JSP页面中直接编写java代码,造成jsp页面难以维护. 二.JSP常用标签 ...

  4. CAIN怎么嗅探路由密码

    Cain & Abel 是由Oxid.it开发的一个针对Microsoft操作系统的免费口令恢复工具.号称穷人使用的L0phtcrack.它的功能十分强大,可以网络嗅探,网络欺骗,破解加密口令 ...

  5. MVC Code First 自动生成数据库

    1.新建一个MVC项目

  6. For Freedom —— 代理篇

    人生在世,总是受到各种约束.心脏跳动都感到困难呢!! 公司内网,安全区,fq等等等~~我们需要一个稳定易用高性能高弹性的代理工具!3Proxy,Here it is, CLICK ME!! 简单介绍下 ...

  7. Linux学习内容

    Linux学习要点(转载自红联) 一.学习Linux的基本要求1. 掌握至少50个以上的常用命令. 2. 熟悉Gnome/KDE等X-windows桌面环境操作 . 3. 掌握.tgz..rpm等软件 ...

  8. 关于“模仿"和”创新“

    互联网刚刚进入中国的前10年,国内互联网企业基本处于模仿和学习阶段.三大门户新浪.搜狐和网易,师从雅虎:现在如日中天的BAT三巨头,百度学习谷歌.阿里巴巴学习亚马逊和EBAY.腾讯学习ICQ. 关于模 ...

  9. Openfire 4.1.0

    http://www.igniterealtime.org/downloads/index.jsp 服务器端口 接口 端口   类型 描述 所有的地址 5222 客户端到服务器 客户端使用标准端口连接 ...

随机推荐

  1. U8g2库I2C总线再次突破性调试成功

    这次采用U8X8的方式,不再采用u8g2,因为后者一直报内存问题.所以采用了不占内存的u8x8模式 同时u8g2库文件的示例代码也是很牛逼的, 里面还有message box 非常的可爱运行效果也非常 ...

  2. 在CMainFrame里使用定时器是有讲究的

    设置定时器函数:SetTimer 单位毫秒 销毁定时器函数:KillTimer 消息:WM_TIMER 注意事项: (1)不要在构造函数里设置定时器. (2)不要在析构函数里销毁定时器. 原因:构造函 ...

  3. DOM4J使用简介

    Dom4j 使用简介 作者:冰云 icecloud(AT)sina.com 时间:2003.12.15   版权声明: 本文由冰云完成,首发于CSDN,未经许可,不得使用于任何商业用途. 文中代码部分 ...

  4. SQL SERVER的单用户模式以及专用管理员连接

    2007-03-08 18:22:03.46 server    Microsoft SQL Server  2000 - 8.00.2039 (Intel X86) May  3 2005 23:1 ...

  5. SEO—Meta标签优化

    Meta标签之一"标题": 标题是网站中很重要的一个标签,他在搜索引擎中是直接显示出来的,一般情况下要网站的核心关键词和网站名称都写进去,这样更有利于网站的排名.但是要注意标题的长 ...

  6. CGroup Namspace

    CGroup 介绍 CGroup 是 Control Groups 的缩写,是 Linux 内核提供的一种可以限制.记录.隔离 进程组 (process groups) 所使用的物力资源 (如 cpu ...

  7. CentOS 下做端口映射/端口转发

    CentOS 下做端口映射/端口转发==[实现目标]==================[服务器A]有2块网卡,一块接内网,一块接外网,[服务器B]只有一块内网网卡:访问[服务器A]的7890端口跳转 ...

  8. event跨进程通信

    event天生的弱势,只有mutex可以感知丢失,就是将另一个进程关闭了,event无法感知. event1: #include <stdio.h> #include <stdlib ...

  9. 安装php扩展phpredis

    下载phpredis-master.tar.gz下载地址:http://pan.baidu.com/s/1i37R8TB 解包tar zxvf phpredis-master.tar.gzcd php ...

  10. ssh 设置私钥实现两台linux主机无密码访问

    在服务器主机上(称为A主机) 创建公钥与私钥: ssh-keygen -t rsa 一路回车,如果想设置密码短语,在提示 passphrase 的时候设置密码短语 查看生成的公钥及私钥: ls ~/. ...