ICQ
我一直都想编一个自己的聊天软件,像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:
- /*
- Navicat MySQL Data Transfer
- Source Server : courseregis
- Source Server Version : 50022
- Source Host : localhost:3306
- Source Database : superqq
- Target Server Type : MYSQL
- Target Server Version : 50022
- File Encoding : 65001
- Date: 2016-07-21 21:46:12
- */
- SET FOREIGN_KEY_CHECKS=0;
- -- ----------------------------
- -- Table structure for failmessage
- -- ----------------------------
- DROP TABLE IF EXISTS `failmessage`;
- CREATE TABLE `failmessage` (
- `id1` bigint(10) NOT NULL,
- `id2` bigint(10) default NULL,
- `time` datetime default NULL,
- `content` varchar(140) default NULL,
- `id` bigint(20) NOT NULL auto_increment,
- PRIMARY KEY (`id`),
- KEY `f3` USING BTREE (`id1`),
- KEY `f4` USING BTREE (`id2`),
- CONSTRAINT `failmessage_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
- CONSTRAINT `failmessage_ibfk_2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='InnoDB free: 3072 kB; (`id1`) REFER `superqq/user`(`id`) ON ';
- -- ----------------------------
- -- Records of failmessage
- -- ----------------------------
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 10:52:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 10:52:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:43:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:43:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:44:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:48:17', '大家好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-17 14:56:17', '你好', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-18 07:55:18', 'NIHAO', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
- INSERT INTO `failmessage` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '');
- -- ----------------------------
- -- Table structure for failrelation
- -- ----------------------------
- DROP TABLE IF EXISTS `failrelation`;
- CREATE TABLE `failrelation` (
- `id1` bigint(10) NOT NULL,
- `id2` bigint(10) NOT NULL,
- PRIMARY KEY (`id1`,`id2`),
- KEY `f2` USING BTREE (`id2`),
- CONSTRAINT `failrelation_ibfk_1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `failrelation_ibfk_2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT COMMENT='InnoDB free: 3072 kB; (`id1`) REFER `superqq/user`(`id`) ON ';
- -- ----------------------------
- -- Records of failrelation
- -- ----------------------------
- INSERT INTO `failrelation` VALUES ('', '');
- INSERT INTO `failrelation` VALUES ('', '');
- INSERT INTO `failrelation` VALUES ('', '');
- INSERT INTO `failrelation` VALUES ('', '');
- -- ----------------------------
- -- Table structure for message
- -- ----------------------------
- DROP TABLE IF EXISTS `message`;
- CREATE TABLE `message` (
- `id1` bigint(10) NOT NULL,
- `id2` bigint(10) NOT NULL,
- `time` datetime NOT NULL,
- `content` varchar(140) NOT NULL,
- `id` bigint(20) NOT NULL auto_increment,
- `d1` bit(1) default '',
- `d2` bit(1) default '',
- PRIMARY KEY (`id`),
- KEY `f3` (`id1`),
- KEY `f4` (`id2`),
- CONSTRAINT `f3` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE,
- CONSTRAINT `f4` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of message
- -- ----------------------------
- INSERT INTO `message` VALUES ('', '', '2016-07-07 10:42:13', 'hello 120 I\'m 119', '1', '', '\0');
- INSERT INTO `message` VALUES ('121', '120', '2016-07-06 10:42:37', 'hello 120 I\'m 121', '', '', '\0');
- INSERT INTO `message` VALUES ('', '', '2016-08-04 10:43:09', 'hello 123 I\'m 120', '3', '', '');
- INSERT INTO `message` VALUES ('120', '119', '2017-12-09 00:00:00', 'test insert time.', '4', '\0', '');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-27 14:00:48', 'hello ', '5', '', '\0');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-31 14:01:10', 'hello', '6', '', '\0');
- INSERT INTO `message` VALUES ('120', '119', '2016-07-08 15:39:49', 'hello', '7', '\0', '');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:43:53', 'hello test date', '8', '', '\0');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:45:59', 'hello test date', '9', '', '\0');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:46:08', 'hello test date', '10', '', '\0');
- INSERT INTO `message` VALUES ('119', '120', '2016-07-08 15:46:43', 'hello test date', '11', '', '\0');
- INSERT INTO `message` VALUES ('120', '124', '2016-07-22 17:47:53', '', '12', '', '');
- INSERT INTO `message` VALUES ('120', '119', '2015-03-03 12:13:14', 'nihao', '13', '\0', '');
- INSERT INTO `message` VALUES ('120', '119', '2016-10-08 10:12:11', '120群发信息。', '14', '\0', '');
- INSERT INTO `message` VALUES ('120', '119', '2016-08-10 14:05:10', '213213', '15', '', '');
- INSERT INTO `message` VALUES ('119', '120', '2016-08-10 17:34:10', '你好--', '18', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:37:10', 'hHh', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:39:10', 'HH', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:42:10', '而且为二次', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:43:10', '年后', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:46:10', '哈哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 17:49:10', '哈哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:11', 'nihao', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:12:10', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 10:11:10', 'nihao', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:20:10', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:21:10', '年号', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:22:10', 'niaoj', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:22:10', '', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 18:25:10', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 19:16:10', 'NIHAO', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 19:16:10', 'NIHAO', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 19:43:10', 'njkfds', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-10 19:43:10', 'fjskadljf dsa', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 10:44:11', '你哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 10:45:11', '哈哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 10:45:11', '你好哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:12:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:13:11', '我很好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:13:11', '年号', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:14:11', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:14:11', '你好O', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:29:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:29:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '你哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:30:11', '恩', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '哈哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '地方', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:33:11', '发', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:38:11', '年后', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:40:11', '年后', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:42:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:47:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:49:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', ' 你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:50:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 11:51:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 14:56:11', '大家好我是Yuan', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 14:59:11', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '你哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:01:11', '表', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:26:11', '你哈', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-11 15:28:11', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-01-12 10:10:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-08 10:02:08', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:12:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:02:17', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-04 05:05:04', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:03:17', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-12 10:02:12', 'hello', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:05:17', '大家好我是120', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:06:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-01 05:04:01', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:09:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:09:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 10:41:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:29:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:30:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:31:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:40:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:40:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:41:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:42:17', '不好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:42:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:43:17', '我是119', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 11:51:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 12:07:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:42:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:42:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:43:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:44:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2017-01-01 05:04:01', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:48:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:49:17', '大家好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:55:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:56:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-17 14:56:17', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-18 07:53:18', 'NIHAO', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-18 07:55:18', 'NIHAO', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-18 07:55:18', 'NIAHO', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-18 07:56:18', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 11:24:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 11:28:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 12:08:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 12:56:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 15:10:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 15:11:21', '你好', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 20:51:21', '你好,我是Mary', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 20:55:21', '收到,我是Yuan', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
- INSERT INTO `message` VALUES ('', '', '2016-08-21 21:07:21', '筒子们,大家好,大家辛苦了', '', '', '');
- -- ----------------------------
- -- Table structure for relation
- -- ----------------------------
- DROP TABLE IF EXISTS `relation`;
- CREATE TABLE `relation` (
- `id1` bigint(10) NOT NULL,
- `id2` bigint(10) NOT NULL,
- PRIMARY KEY (`id1`,`id2`),
- KEY `f2` (`id2`),
- CONSTRAINT `f1` FOREIGN KEY (`id1`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT `f2` FOREIGN KEY (`id2`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of relation
- -- ----------------------------
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- INSERT INTO `relation` VALUES ('', '');
- -- ----------------------------
- -- Table structure for user
- -- ----------------------------
- DROP TABLE IF EXISTS `user`;
- CREATE TABLE `user` (
- `id` bigint(10) NOT NULL auto_increment,
- `name` varchar(20) default NULL,
- `pwd` varchar(32) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of user
- -- ----------------------------
- INSERT INTO `user` VALUES ('', 'Jiaxin', '7e1cd7dca89a1678042477183b7ac3f');
- INSERT INTO `user` VALUES ('', 'Yuan', 'c6f057b86584942e415435ffb1fa93d4');
- INSERT INTO `user` VALUES ('', 'Xuewei', '4c56ff4ce4aaf9573aa5dff913df997a');
- INSERT INTO `user` VALUES ('', 'Yaze', 'a0a080f42e6f13b3a2df133f073095dd');
- INSERT INTO `user` VALUES ('', 'Tom', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'John', 'c8ffe9a587b126f152ed3d89a146b445');
- INSERT INTO `user` VALUES ('', 'Yunchen', '3def184ad8f4755ff269862ea77393dd');
- INSERT INTO `user` VALUES ('', 'M', '9b8619251a19057cff70779273e95aa6');
- INSERT INTO `user` VALUES ('', 'Silly', '65ded5353c5ee48d0b7d48c591b8f430');
- INSERT INTO `user` VALUES ('', 'Tikky', '9fc3d7152ba9336a670e36d0ed79bc43');
- INSERT INTO `user` VALUES ('', '', '1385974ed5904a438616ff7bdb3f7439');
- INSERT INTO `user` VALUES ('', 'Mary', '7ef605fc8dba5425d6965fbd4c8fbe1f');
- INSERT INTO `user` VALUES ('', 'Yane', 'b73ce398c39f506af761d2277d853a92');
- INSERT INTO `user` VALUES ('', 'jiaGu', '37a749d808e46495a8da1e5352d03cae');
- INSERT INTO `user` VALUES ('', 'YY', 'da4fb5c6e93e74d3df8527599fa62642');
- INSERT INTO `user` VALUES ('', 'Yane', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Yanem', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Y', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'YY', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'ZZ', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'X', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'X', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'te', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Marry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Marry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Gray', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Y', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Velly', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Harry', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Harry', 'c20ad4d76fe97759aa27a0c99bff6710');
- INSERT INTO `user` VALUES ('', 'Harray', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Hyne', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Hyne', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Tedr', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Tedr', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Ted', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'YaneZane', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'YaneZanen', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Trne', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Tone', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Mary', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Hery', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Tommas', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Johnson', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', '刘远圳', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', 'Torrorrent', '202cb962ac59075b964b07152d234b70');
- INSERT INTO `user` VALUES ('', '基友小花', '202cb962ac59075b964b07152d234b70');
数据库操作类dao.java:
- package dao;
- import java.math.BigInteger;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.Date;
- import java.util.GregorianCalendar;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Vector;
- import model.message;
- import model.relation;
- import model.user;
- public class dao{
- static String username="root";
- static String pwd = "";
- static String url = "jdbc:mysql://127.0.0.1:3306/superqq";
- static String driver = "org.gjt.mm.mysql.Driver";
- static Connection con;
- static Statement statement;
- public dao(){}
- public static void main(String[] args){
- dao d = new dao();
- }
- 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();
- }
- private void start(){
- try {
- Class.forName( driver );
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- System.out.println("error in loading driver.");
- }
- try {
- con = DriverManager.getConnection(url,username,pwd);
- statement = con.createStatement();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in connect database.");
- }
- }
- private void close(){
- try {
- statement.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in close statement.");
- }
- try {
- con.close();
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in close connection.");
- }
- }
- public user getUser(String id){
- start();
- List<user> li = new LinkedList<user>();
- try {
- ResultSet re = statement.executeQuery("select * from user where id ="+id+";");
- while(re.next()){
- li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getUser("+id+")");
- }
- finally{close();}
- return li.get(0);
- }
- public user getUser(String name,String pwd){
- start();
- List<user> li = new LinkedList<user>();
- try {
- ResultSet re = statement.executeQuery("select * from user where name ='"+name+"';");
- while(re.next()){
- li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getUser("+name+","+pwd+")");
- }
- finally{close();}
- if(li.size()!=0){
- return li.get(0);
- }else{
- return null;
- }
- }
- public List<relation> getRelation(String id){
- start();
- List<relation> li = new LinkedList<relation>();
- try {
- statement = con.createStatement();
- ResultSet re = statement.executeQuery("select * from relation where id1 ="+id+"||id2 ="+id+";");
- while(re.next()){
- li.add(new relation(re.getString(1),re.getString(2)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getRelation("+id+")");
- }
- finally{close();}
- return li;
- }
- public List<user> getUserList(){
- start();
- List<user> li=new LinkedList<user>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from user;");
- while(re.next()){
- li.add(new user(re.getString(1),re.getString(2),re.getString(3)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- finally{close();}
- return li;
- }
- public Boolean addUser(user u){
- start();
- Boolean flag = true;
- try {
- statement.execute("insert into user(name,pwd) values('"+u.getUsername()+"','"+u.getPwd()+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in addUser:"+u);
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean deleteUser(String id){
- start();
- Boolean flag = true;
- try {
- statement.execute("delete from user where id ='"+id+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in deleteUser:id="+id);
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean updateUser(user u){
- start();
- Boolean flag=true;
- try {
- statement.execute("update user set name='"+u.getUsername()+"',pwd ='"+u.getPwd()+"' where id ='"+u.getId()+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in update:"+u);
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean updatePwd(user u){
- start();
- Boolean flag=true;
- try {
- statement.execute("update user set pwd='"+u.getUsername()+"' where id ='"+u.getId()+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in updatepwd:"+u);
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public List<relation> getRelation(){
- start();
- List<relation> li=new LinkedList<relation>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from relation;");
- while(re.next()){
- li.add(new relation(re.getString(1),re.getString(2)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getRelation().");
- }
- finally{close();}
- return li;
- }
- public Boolean addRelation(relation r){//先对id1,id2排序,再插入
- start();
- Boolean flag = true;
- try {
- String id1 = r.getId1();
- String id2 = r.getId2();
- if(new Integer(id1).intValue()>new Integer(id2).intValue()){
- String id = id1;
- id1 = id2;
- id2 = id;
- }
- statement.execute("insert into relation(id1,id2) values('"+id1+"','"+id2+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in addRelation:"+r);
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean deleteRelation(relation r){//确保id有序(非减)
- start();
- Boolean flag = true;
- try {
- String id1 = r.getId1();
- String id2 = r.getId2();
- if(new Integer(id1).intValue()>new Integer(id2).intValue()){
- String id = id1;
- id1 = id2;
- id2 = id;
- }
- statement.execute("delete from relation where id1 = '"+id1+"'&&id2 ='"+id2+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in deleteRelation("+r+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public List<relation> getFailRelation(String id){
- start();
- List<relation> li=new LinkedList<relation>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from failrelation where id2 = '"+id+"';");
- while(re.next()){
- li.add(new relation(re.getString(1),re.getString(2)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getFailRelation:id="+id);
- }
- finally{close();}
- return li;
- }
- public Boolean addFailRelation(relation r){
- start();
- Boolean flag =true;
- try {
- statement.execute("insert into failrelation(id1,id2) values('"+r.getId1()+"','"+r.getId2()+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in addFailRelation("+r+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean deleteFailRelation(relation r){
- start();
- Boolean flag = true;
- try {
- statement.execute("delete from failrelation where (id1='"+r.getId1()+"'&&id2 ='"+r.getId2()+"')||(id1='"+r.getId2()+"'&&id2='"+r.getId1()+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in deleteFailRelation("+r+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public List<user> getFriend(String id){
- start();
- List<user> li=new LinkedList<user>();
- ResultSet re;
- try {
- 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);");
- while(re.next()){
- li.add(new user(re.getString(1),re.getString(2)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getFriend("+id+").");
- }
- finally{close();}
- return li;
- }
- public Boolean addmessage(message msg){
- start();
- Boolean flag = true;
- try {
- statement.execute("insert into message(id1,id2,time,content) values('"+msg.getId1()+"','"+msg.getId2()+"','"+msg.getDate().toLocaleString()+"','"+msg.getContent()+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- System.out.println("error in addmessage("+msg+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public List<message> getfailmessage(String id){
- start();
- List<message> li=new LinkedList<message>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from failmessage where id2 = '"+id+"';");
- while(re.next()){
- Date date = convertToDate(re.getString(3));
- li.add(new message(re.getString(1),re.getString(2),date,re.getString(4)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getfailmessage("+id+").");
- }
- finally{close();}
- return li;
- }
- public Boolean addfailmessage(message msg){
- start();
- Boolean flag =true;
- try {
- statement.execute("insert into failmessage(id1,id2,time,content) values('"+msg.getId1()+"','"+msg.getId2()+"','"+msg.getDate().toLocaleString()+"','"+msg.getContent()+"');");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in addfailmessage("+msg+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public Boolean deletefailmessage(message msg){//待修正--应用id确定被删除离线消息
- start();
- Boolean flag = true;
- try {
- statement.execute("delete from failmessage where id1 = '"+msg.getId1()+"'&&id2 ='"+msg.getId2()+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in deletefailmessage("+msg+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public List<message> getMessage(){
- start();
- List<message> li=new LinkedList<message>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from message;");
- while(re.next()){
- li.add(new message(re.getString(1),re.getString(2),re.getDate(3),re.getString(4)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getMessage().");
- }
- finally{close();}
- return li;
- }
- public List<message> getMessage(String id){
- start();
- List<message> li = new LinkedList<message>();
- try {
- ResultSet re = statement.executeQuery("select * from message where id1 ="+id+";");
- while(re.next()){
- String str = re.getString(3);
- 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();
- li.add(new message(re.getString(1),re.getString(2),date,re.getString(4)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in getMessage("+id+")");
- }
- return li;
- }
- public List<message> getMessage(String id1,String id2){//注意顺序,id1 查询与 id2的聊天记录。
- start();
- List<message> li=new LinkedList<message>();
- ResultSet re;
- try {
- re = statement.executeQuery("select * from message where (d1=1&&id1='"+id1+"'&&id2='"+id2+"')||(d2=1&&id1='"+id2+"'&&id2='"+id1+"') order by time ASC;");
- while(re.next()){
- li.add(new message(re.getString(1),re.getString(2),re.getDate(3),re.getString(4)));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- System.out.println("error in getMessage("+id1+","+id2+").");
- }
- finally{close();}
- return li;
- }
- public Boolean deleteMessage(String id1,String id2){
- start();
- Boolean flag = true;
- try {
- statement.execute("update message set d1 = 0 where id1 ='"+id1+"'&&id2='"+id2+"';");
- statement.execute("update message set d2 = 0 where id2 ='"+id1+"'&&id1='"+id2+"';");
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- System.out.println("error in deleteMessage("+id1+","+id2+").");
- flag = false;
- }
- finally{close();}
- return flag;
- }
- public void md(){
- start();
- try{
- ResultSet re=statement.executeQuery("select id,pwd from user;");
- Vector<String> id=new Vector<String>();
- Vector<String> pwd=new Vector<String>();
- while(re.next()){
- id.add(re.getString(1));
- pwd.add(re.getString(2));
- }
- re.close();
- while(!id.isEmpty()){
- statement.execute("update user set pwd='"+encryp(pwd.remove(0))+"' where id='"+id.remove(0)+"';");
- }
- }catch(SQLException e){
- e.printStackTrace();
- }
- finally{
- close();
- }
- return;
- }
- 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);
- }
- }
服务器端程序Server.java
- package control;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.sql.SQLException;
- import java.util.Date;
- import java.util.GregorianCalendar;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.logging.Logger;
- import model.message;
- import model.relation;
- import model.user;
- import dao.dao;
- public class Server implements Runnable{
- List<user> li = new LinkedList<user>();//在线用户列表
- List<Socket> li_socket = new LinkedList<Socket>();
- ServerSocket server;
- Socket socket ;
- Object lock = new Object();
- Logger Log = Logger.getGlobal();
- public Server(int port,int queueLength){
- try{
- server = new ServerSocket(port,queueLength);//port,queueLength
- }catch(Exception e){}
- System.out.println("服务器创建成功。");
- }
- public List<user> getLi() {
- return li;
- }
- public void start(){
- System.out.println("服务器已启动……"+server);
- while(true){
- try{
- socket = server.accept();//系统在这里等待连接
- new Thread(this).start();
- System.out.println(socket.getInetAddress()+"连接服务器成功。");
- }catch(Exception e){
- System.out.println("server error");
- try{
- socket.close();
- }catch(Exception ee){}
- close();
- }
- }
- }
- //主循环,根据请求码处理用户请求
- public void run(){//线程处理代码段,用以监听与客户端的连接。
- Socket socket = this.socket;
- BufferedReader input;
- PrintWriter output;
- String str = "";
- try {
- input =new BufferedReader( new InputStreamReader(socket.getInputStream()));//线程在这里等待输入流
- output =new PrintWriter( new OutputStreamWriter(socket.getOutputStream()),true);
- while(true){
- //00:登录
- //10:查询与指定好友的历史消息
- //11:点对点发msg
- //12:群发好友msg
- //13:删除历史消息
- //20:获得好友列表
- //21:添加好友
- //22:删除好友
- //23:确认添加好友
- //24:拒绝好友请求
- //30:更新用户信息
- //40:注册新用户
- Thread.sleep(1000);
- try{
- str = input.readLine();
- System.out.println("服务器收到:"+str);
- }catch(Exception e){
- socket.close();
- System.out.println("监听断开");
- break;
- }
- String cmd="";
- if(str!=null&&str.length()>2){
- cmd= str.substring(0,2);
- }
- synchronized (lock) {//synchronized
- try{
- checkStatus();
- switch(cmd){
- case "00":{//处理结果:给客户端发送用户与朋友信息;登录
- str = str.substring(3).trim();
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数错误。");
- output.println("000");
- break;
- }
- String id = para[0];
- String pwd = para[1];
- user u = new user(id,"*",pwd);
- if(login(u)){
- System.out.println(u+"\t 登录成功。");
- u = getUser(u.getId());
- li.add(u);
- li_socket.add(socket);
- List<user> f_li = getFriend(id);
- String str_f = u.getId()+","+u.getUsername()+";";
- for(user each:f_li){
- str_f = str_f + each.getId()+","+each.getUsername()+";";
- }
- List<relation> li_r = this.getFailRelation(id);
- String str_r ="";
- for(relation r:li_r){
- str_r = str_r +r.toString()+";";
- }
- List<message> li_m = this.getfailmessage(id);
- String str_m = "";
- for(message msg:li_m){
- str_m =str_m+msg.toString()+";";
- }
- str = "001:"+str_f+"&$"+str_r+"&$"+str_m;
- output.println(str);
- for(message msg:li_m){
- deletefailmessage(msg);
- }
- System.out.println("登录处理完成:"+str);
- }else{
- output.println("000");
- System.out.println(id+"\t登录失败");
- }
- };break;
- case "10":{//发送聊天记录序列,查询与指定好友的历史消息
- str = str.substring(3).trim();
- String para[] = str.split(",");
- if(para.length!=2){
- System.out.println("参数错误。");
- output.println("100");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- System.out.println("10:查询与指定好友聊天记录。"+id1+","+id2);
- List<message> m_li = this.getMessage(id1, id2);
- String m_str ="";
- for(message msg:m_li){
- m_str =m_str + msg.toString()+";";
- }
- output.println("101:"+m_str);
- System.out.println("聊天记录查询成功:"+m_str);
- };break;
- case "11":{//点对点发msg
- System.out.println("点对点msg.");
- str = str.substring(3).trim();
- String[] para = str.split(",");
- if(para.length!=4){
- System.out.println("参数不匹配。");
- output.println("110");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- System.out.println("para[2]:"+para[2]);
- Date date =convertToDate(para[2]);
- System.out.println("date:"+date);
- String content = para[3];
- message msg = new message(id1,id2,date,content);
- if(send(id2,"111:"+msg.toString())){
- System.out.println("转发成功:"+msg.toString());
- addmessage(msg);//发送成功后把消息存入数据库
- break;
- }else{
- System.out.println("目标用户未在线。");
- this.addfailmessage(msg);//发送不成功存入离线记录表
- System.out.println("转至离线消息");
- }
- };break;
- case "12":{//群发好友msg
- System.out.println("12:群发好友信息。");
- str = str.substring(3).trim();
- String[] para = str.split(",");
- if(para.length!=4||!para[0].equals(para[1])){
- System.out.println("参数不匹配。");
- output.println("120");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- Date date = convertToDate(para[2]);
- String content = para[3];
- List<user> li_f = getFriend(id1);
- message msg = new message(id1,id2,date,content);
- for(int i=0;i<li_f.size();i++){
- //Boolean flag = false;
- id2 = li_f.get(i).getId();
- msg.setId2(id2);
- if(send(id2,"121:"+msg.toString())){
- addmessage(msg);
- System.out.println("群发消息至"+id2+"成功。");
- }else{
- addfailmessage(msg);
- System.out.println("转至离线消息:"+msg);
- }
- }
- //socket = socket_temp;
- output.println("121");
- System.out.println("群发消息处理成功。");
- };break;
- case "13":{//删除历史消息
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("130");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- if(deleteMessage(id1,id2)){
- System.out.println("历史消息清空:"+id1+","+id2);
- output.println("131");
- }else{
- System.out.println("清空失败:"+id1+","+id2);
- output.println("130");
- }
- };break;
- case "20":{//获得好友列表
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=1){
- System.out.println("参数不匹配。");
- output.println("200");
- break;
- }
- String id = para[0];
- List<user> li_f = getFriend(id);
- String str_f = "";
- for(user u:li_f){
- str_f = str_f + u.toString()+";";
- }
- output.println("201:"+str_f);
- System.out.println("成功获取好友列表。");
- };break;
- case "21":{//添加好友
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("210");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- //relation r = new relation((new Integer(id1).intValue()>new Integer(id2).intValue()?id2:id1),(new Integer(id1).intValue()>new Integer(id2).intValue()?id1:id2));
- relation r = new relation(id1,id2);
- addFailRelation(r);
- System.out.println("add temp relation:"+r);
- if(send(id2,"211:"+id1)){
- System.out.println("发出添加好友通知。");
- }else{
- System.out.println("添加好友失败。");
- }
- };break;
- case "22":{//删除好友
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("220");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- if(new Integer(id1).intValue()>new Integer(id2).intValue()){
- String temp = id1;
- id1 = id2;
- id2 = temp;
- }
- relation r = new relation(id1,id2);
- if(deleteRelation(r)){
- System.out.println("删除好友关系:"+id1+","+id2+" 成功。");
- if(send(id2,"221:"+id1)){
- System.out.println("删除好友通知完成。");
- output.println("221:"+id2);
- }else{
- System.out.println("删除好友通知失败。");
- }
- }else{
- System.out.println("删除好友关系失败。");
- output.println("220");
- }
- };break;
- case "23":{//确认添加好友
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("230");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- relation r = new relation(id1,id2);
- if(addRelation(r)){
- deleteFailRelation(r);
- System.out.println("确认添加好友关系:"+id1+","+id2+" 成功。");
- if(send(id2,"231:"+id1+","+getUser(id1).getUsername())){
- System.out.println("添加好友通知完成。");
- output.println("231:"+id2+","+getUser(id2).getUsername());
- }else{
- System.out.println("添加好友通知失败。");
- output.println("230");
- }
- }else{
- System.out.println("确认添加好友关系失败。");
- output.println("230");
- }
- };break;
- case "24":{//拒绝好友请求
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("240");
- break;
- }
- String id1 = para[0];
- String id2 = para[1];
- relation r = new relation(id1,id2);
- if(deleteFailRelation(r)){
- if(send(id2,"241:"+id1)){
- System.out.println("拒绝好友通知完成。");
- }else{
- System.out.println("拒绝好友通知失败。");
- output.println("240");
- }
- }else{
- System.out.println("拒绝添加好友失败。");
- output.println("240");
- }
- };break;
- case "30":{//更改用户名
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=3){
- System.out.println("参数不匹配。");
- output.println("300");
- break;
- }
- String id = para[0];
- String name = para[1];
- String pwd = para[2];
- user u = new user(id,name,pwd);
- if(verify(u)){
- System.out.println("验证成功:"+u);
- if(updateUser(u)){
- System.out.println("用户信息更新成功。");
- output.println("301:"+u.toString());
- }else{
- System.out.println("用户信息更新失败。");
- output.println("300");
- }
- }else{
- System.out.println("验证失败。");
- output.println("300");
- }
- };break;
- case "31":{//更改用户密码
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=3){
- System.out.println("参数不匹配。");
- output.println("310");
- break;
- }
- String id = para[0];
- String name = para[1];
- String pwd = para[2];
- user u = new user(id,name,pwd);
- if(verify(u)){
- System.out.println("验证成功:"+u);
- if(updatePwd(u)){
- System.out.println("用户信息更新成功。");
- u = getUser(id);
- output.println("301:"+u.toString());
- }else{
- System.out.println("用户信息更新失败。");
- output.println("300");
- }
- }else{
- System.out.println("验证失败。");
- output.println("300");
- }
- };break;
- case "40":{//注册新用户
- str = str.substring(3);
- String[] para = str.split(",");
- if(para.length!=2){
- System.out.println("参数不匹配。");
- output.println("400");
- break;
- }
- String name = para[0];
- String pwd = para[1];
- user u = new user("*",name,pwd);
- if(register(u)){
- u = getUser(name,pwd);
- System.out.println("用户注册成功。");
- output.println("401:"+u.toString());
- }else{
- System.out.println("用户注册失败");
- output.println("400");
- }
- };break;
- case "55":output.println("echo\t"+str.substring(2));break;
- default:{
- System.out.println("请求码匹配失败。");
- output.println("-1");
- };break;
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }//synchronized
- }
- }catch(Exception e){
- try{
- socket.close();
- System.out.println("服务器出现异常。");
- e.printStackTrace();
- }catch(Exception ee){}
- }
- }
- private void checkStatus(){//需要注意删除
- for(int i=0;i<li_socket.size();i++){
- System.out.println("检查第"+i+"个连接的状态。");
- if(!li_socket.get(i).isBound()){
- li.remove(i);
- li_socket.remove(i);
- System.out.println("清除第"+i+"个连接。");
- i--;
- }
- }
- System.out.println("状态扫描完成。");
- }
- 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();
- }
- private Boolean send(String id,String str){
- System.out.println("开始转发");
- Boolean flag = false;
- for(int i=0;i<li.size();i++)
- {
- if(id.equals(li.get(i).getId())){
- Socket socket = li_socket.get(i);
- PrintWriter output;
- try {
- output = new PrintWriter( new OutputStreamWriter(socket.getOutputStream()),true);
- output.println(str);
- output.flush();
- System.out.println("转发完成");
- flag =true;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- flag = false;
- System.out.println("error in send"+i+","+str);
- }
- }
- }
- return flag;
- }
- private String receive(){
- String str ="";
- BufferedReader input =null;
- try{
- input =new BufferedReader( new InputStreamReader(socket.getInputStream()));//线程在这里等待输入流
- while(str.equals("")){
- str = input.readLine();
- }
- }catch(Exception e){
- System.out.println("socket 接收出错。");
- }finally{
- try {
- input.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- return str;
- }
- private List<user> getUserList(){
- return new dao().getUserList();
- }
- private Boolean register(user u){
- user u_temp = new dao().getUser(u.getUsername(), u.getPwd());
- Boolean flag = false;
- if(u_temp==null){
- new dao().addUser(u);
- flag = true;
- }else{
- flag = false;
- }
- return flag;
- }
- private Boolean login(user u){
- if(verify(u)){
- return true;
- }else{
- return false;
- }
- }
- private Boolean verify(user u){
- user du = getUser(u.getId());
- return du.getPwd().equals(u.getPwd());
- }
- private user getUser(String id){
- return new dao().getUser(id);
- }
- private user getUser(String name,String pwd){
- return new dao().getUser(name,pwd);
- }
- private Boolean deleteUser(String id){
- return new dao().deleteUser(id);
- }
- private Boolean updateUser(user u){
- return new dao().updateUser(u);
- }
- private Boolean updatePwd(user u){
- return new dao().updatePwd(u);
- }
- private List<relation> getRelation(){
- return new dao().getRelation();
- }
- private Boolean addRelation(relation r){
- return new dao().addRelation(r);
- }
- private Boolean deleteRelation(relation r){
- return new dao().deleteRelation(r);
- }
- private List<relation> getFailRelation(String id){
- return new dao().getFailRelation(id);
- }
- private Boolean addFailRelation(relation r){
- return new dao().addFailRelation(r);
- }
- private Boolean deleteFailRelation(relation r){
- return new dao().deleteFailRelation(r);
- }
- private List<user> getFriend(String id){
- return new dao().getFriend(id);
- }
- private Boolean addmessage(message msg){
- return new dao().addmessage(msg);
- }
- private List<message> getfailmessage(String id){
- return new dao().getfailmessage(id);
- }
- private Boolean addfailmessage(message msg){
- return new dao().addfailmessage(msg);
- }
- private Boolean deletefailmessage(message msg){
- return new dao().deletefailmessage(msg);
- }
- private List<message> getMessage(String id)//指定用户聊天记录
- {
- return new dao().getMessage(id);
- }
- private List<message> getMessage(String id1,String id2)//特定的两人的聊天记录
- {
- return new dao().getMessage(id1, id2);
- }
- private List<message> getMessage()//所有聊天记录
- {
- return new dao().getMessage();
- }
- private Boolean deleteMessage(String id1,String id2){
- return new dao().deleteMessage(id1, id2);
- }
- public void close()//关闭服务器;
- {
- try {
- server.close();
- System.out.println("服务器已关闭");
- } catch (IOException e) {
- // TODO Auto-generated catch block
- System.out.println("服务器关闭出错。");
- }
- }
- }
服务器界面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的更多相关文章
- 用ASP.Net写一个发送ICQ信息的程序
用ASP.Net写一个发送ICQ信息的程序 这里我给大家提供一个很实用的例子,就是在线发送ICQ信息.想一想我们在网页上直接给朋友发送ICQ信息,那是多么美妙的事情啊.呵呵,在吹牛啊,其实ICQ本来就 ...
- 几款web版整合(QQ、msn、icq、yahoo通、Gtalk等)即时聊天http://hi.baidu.com/ejie/blog/item/e89794ef9a9431efce1b3ebd.html
直到近期为止,我们经常使用的即时聊天工具(QQ.msn等)了Web版,大家不用下载庞大软件,直接打开网页就能够与自己的好友聊天,很方便.在此将时汇总,便于大家查找,节约大家一点时间. 此都是官 ...
- java web学习总结(二十七) -------------------JSP标签介绍
一.JSP标签介绍 JSP标签也称之为Jsp Action(JSP动作)元素,它用于在Jsp页面中提供业务逻辑功能,避免在JSP页面中直接编写java代码,造成jsp页面难以维护. 二.JSP常用标签 ...
- CAIN怎么嗅探路由密码
Cain & Abel 是由Oxid.it开发的一个针对Microsoft操作系统的免费口令恢复工具.号称穷人使用的L0phtcrack.它的功能十分强大,可以网络嗅探,网络欺骗,破解加密口令 ...
- MVC Code First 自动生成数据库
1.新建一个MVC项目
- For Freedom —— 代理篇
人生在世,总是受到各种约束.心脏跳动都感到困难呢!! 公司内网,安全区,fq等等等~~我们需要一个稳定易用高性能高弹性的代理工具!3Proxy,Here it is, CLICK ME!! 简单介绍下 ...
- Linux学习内容
Linux学习要点(转载自红联) 一.学习Linux的基本要求1. 掌握至少50个以上的常用命令. 2. 熟悉Gnome/KDE等X-windows桌面环境操作 . 3. 掌握.tgz..rpm等软件 ...
- 关于“模仿"和”创新“
互联网刚刚进入中国的前10年,国内互联网企业基本处于模仿和学习阶段.三大门户新浪.搜狐和网易,师从雅虎:现在如日中天的BAT三巨头,百度学习谷歌.阿里巴巴学习亚马逊和EBAY.腾讯学习ICQ. 关于模 ...
- Openfire 4.1.0
http://www.igniterealtime.org/downloads/index.jsp 服务器端口 接口 端口 类型 描述 所有的地址 5222 客户端到服务器 客户端使用标准端口连接 ...
随机推荐
- U8g2库I2C总线再次突破性调试成功
这次采用U8X8的方式,不再采用u8g2,因为后者一直报内存问题.所以采用了不占内存的u8x8模式 同时u8g2库文件的示例代码也是很牛逼的, 里面还有message box 非常的可爱运行效果也非常 ...
- 在CMainFrame里使用定时器是有讲究的
设置定时器函数:SetTimer 单位毫秒 销毁定时器函数:KillTimer 消息:WM_TIMER 注意事项: (1)不要在构造函数里设置定时器. (2)不要在析构函数里销毁定时器. 原因:构造函 ...
- DOM4J使用简介
Dom4j 使用简介 作者:冰云 icecloud(AT)sina.com 时间:2003.12.15 版权声明: 本文由冰云完成,首发于CSDN,未经许可,不得使用于任何商业用途. 文中代码部分 ...
- SQL SERVER的单用户模式以及专用管理员连接
2007-03-08 18:22:03.46 server Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:1 ...
- SEO—Meta标签优化
Meta标签之一"标题": 标题是网站中很重要的一个标签,他在搜索引擎中是直接显示出来的,一般情况下要网站的核心关键词和网站名称都写进去,这样更有利于网站的排名.但是要注意标题的长 ...
- CGroup Namspace
CGroup 介绍 CGroup 是 Control Groups 的缩写,是 Linux 内核提供的一种可以限制.记录.隔离 进程组 (process groups) 所使用的物力资源 (如 cpu ...
- CentOS 下做端口映射/端口转发
CentOS 下做端口映射/端口转发==[实现目标]==================[服务器A]有2块网卡,一块接内网,一块接外网,[服务器B]只有一块内网网卡:访问[服务器A]的7890端口跳转 ...
- event跨进程通信
event天生的弱势,只有mutex可以感知丢失,就是将另一个进程关闭了,event无法感知. event1: #include <stdio.h> #include <stdlib ...
- 安装php扩展phpredis
下载phpredis-master.tar.gz下载地址:http://pan.baidu.com/s/1i37R8TB 解包tar zxvf phpredis-master.tar.gzcd php ...
- ssh 设置私钥实现两台linux主机无密码访问
在服务器主机上(称为A主机) 创建公钥与私钥: ssh-keygen -t rsa 一路回车,如果想设置密码短语,在提示 passphrase 的时候设置密码短语 查看生成的公钥及私钥: ls ~/. ...