a8edb2588581fa8ba386b41bf271da8bdb085355.svn-base 32.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
package com.gx.obe.server.im.serverthread;

import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gx.obe.server.common.utils.IDUtils;
import com.gx.obe.server.im.ChatConstants;
import com.gx.obe.server.im.IMConstants;
import com.gx.obe.server.im.SendFileParam;
import com.gx.obe.server.im.enumeration.EmployeeEnum;
import com.gx.obe.server.im.listener.ServerInfoListener;
import com.gx.obe.server.im.serverthread.ClientChatThread.ChatListener;
import com.gx.obe.server.im.serverthread.LixianWenJian.SendFilter;
import com.gx.obe.server.im.serverthread.SendFileThread.ServerSendFileListener;
import com.gx.obe.server.management.im.entity.Employee;
import com.gx.obe.server.management.im.entity.GroupItem;
import com.gx.obe.server.management.im.entity.GroupMessage;
import com.gx.obe.server.management.im.service.EmployeeService;
import com.gx.obe.server.management.im.service.GroupItemService;
import com.gx.obe.server.management.im.service.GroupMessageService;

@Component
public class IMServerAdapter {
	@Autowired
	private GroupMessageService groupMessageService;
	@Autowired
	private GroupItemService groupItemService;
	@Autowired
	private EmployeeService employeeService;
	
	
	  public static IMServerAdapter serverAdapter;
	  @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
	  public void init() {
		  serverAdapter= this;
		  serverAdapter.groupMessageService= this.groupMessageService;
		  serverAdapter.groupItemService= this.groupItemService;
		  serverAdapter.employeeService= this.employeeService;
	  }

	private static Logger LOG = org.slf4j.LoggerFactory.getLogger(ImServer.class);

//	private Info info;
//	public ImServer(Info info) {
//		this.info = info;
//	}

//	private Socket clientChatWindowSocket;
	private ServerSocket chatSocket, serverConnectionSocket;
	
	private List<ClientChatThread> chatWindowSocketList;// 存储已开始聊天窗口的聊天对话
	
	private List<ClientBean> clientBeanList;// 存储连接到服务器的终端

	private static final Integer MAX_LENGTH = 1024;
	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String UPFILE = "/upfiles/";
	public static final String FG = "/";
	public static final String FENGEFU = ","; //分隔符
	public static final int DELETE_TEMP_DAY_COUNT = 2; // 超过2天的临时消息 记录删除
	public static final int DELETE_TEMP_HOUR = 2;// 每天执行删除临时消息的时间(小时)(24小时制)
	public static final int DELETE_TEMP_MINUTE = 48;
	public static final int CLEAR_SLEEP_TIME = 59000;// 每隔59秒执行一次在线用户检查

	public static final int LINE_COUNT = 12; // 文本区中最多显示多少行数据,就自动清屏

	private String serverIp;
	private Integer chatPort;
	private Integer serverPort;
	private boolean serverStartSuccess = false;
	private boolean useEmployee = false;
	private ChatListenerThread chatListenerThread;
	
	private ServerInfoListener serverInfoListener;
	
	
 	public static IMServerAdapter getInstance(){
		if(null != serverAdapter){
			return serverAdapter;
		}
		serverAdapter = new IMServerAdapter();
		return serverAdapter;
	}
	public void setUseEmployee(boolean useEmployee){
		this.useEmployee = useEmployee;
	}
	public void addserverInfoListener(ServerInfoListener serverInfoListener){
		this.serverInfoListener = serverInfoListener;
	}
	public boolean isStart(){
		return serverStartSuccess;
	}
	
	/**
	 * @Description: 启动服务器,并监听是否开启一个聊天socket
	 * @author guoyr
	 * @param serverIp
	 * @param chatPort
	 * @param serverPort
	 * @return 
	 */
	public boolean startServer(String serverIp, int chatPort, int serverPort) {
		if(serverStartSuccess){
			return serverStartSuccess;
		}
		this.serverIp = serverIp;
		this.chatPort = chatPort;
		this.serverPort = serverPort;
//		shouPort = Integer.parseInt(PropertiesUtil.getProperty(PropertieEnum.RECEIVE_PORT, "1989"));
		// 存储连接到服务器的终端
		clientBeanList = new ArrayList<ClientBean>();
		// 存储已开始聊天窗口的聊天对话
		chatWindowSocketList = new ArrayList<ClientChatThread>();
		try {
			serverConnectionSocket = new ServerSocket(serverPort);
			serverConnectionSocket.setReceiveBufferSize(MAX_LENGTH);
			serverStartSuccess = true;
			// 启动客户端连接监听线程
			ConnectionListenerThread connectionListenerThread = new ConnectionListenerThread();
			connectionListenerThread.start();
		} catch (BindException e) {
			LOG.error(e.getMessage());
			serverStartSuccess = false;
			System.exit(0);
		} catch (IOException e) {
			LOG.error(e.getMessage());
		}
		try {
			// 启动聊天监听线程,监听是否有聊天请求
			chatSocket = new ServerSocket(chatPort);
			chatSocket.setReceiveBufferSize(8192);

			// 启动监听是否始一个新的聊天线程
			chatListenerThread = new ChatListenerThread();
			chatListenerThread.start();
		} catch (BindException ex) {
			serverStartSuccess = false;
		} catch (IOException ex) {
			serverStartSuccess = false;
		}

		if (serverStartSuccess) {

			if (null != serverInfoListener) {
				serverInfoListener.info(new Date(), "  服务器启动成功 !", true);
			}
			new CheckClientState().start(); 
			return true;
		} else {
			if (null != serverInfoListener) {
				serverInfoListener.info(new Date(), "  服务器启动失败 !", false);
				serverInfoListener.info(new Date(), "  服务器IP:"+serverIp+"服务器端口:"+serverPort+"聊天端口:"+chatPort);
			}
			closeServer();
			return false;
		}

	}

	/** 
	 * @Description: 客户端连接监听线程,监听是否有终端连接服务器 
	 * @author guoyr 
	 */
	class ConnectionListenerThread implements Runnable {

		Thread thread = null;

		public void start() {
			thread = new Thread(this);
			thread.setName("客户端连接监听线程");
			thread.start();
		}

		public void stop() {
			thread = null;
		}

		public void run() {
			final ServerListener clientListener = createClisConnectoinListener();
			List<Socket> sockeList = new ArrayList<Socket>();
			while (null != thread && serverStartSuccess) {
				try {
					Socket newClientConnectSocket = serverConnectionSocket.accept();
					sockeList.add(newClientConnectSocket);
					// 当有客户端连接到服务器后,启动一个客户端线程,获得客户端的socket并修改和处理客户端的消息
					ClientBean client = new ClientBean(serverIp, newClientConnectSocket,clientListener);
					client.start();

				} catch (IOException e) {
				}

			}
			for (Socket socket : sockeList) {
				try {
					socket.close();
				} catch (IOException e) {
				}
			}
			sockeList.clear();
		}

	}

	/** 
	 * @Description: 监听是否始一个新的聊天线程 
	 * @author guoyr 
	 */
	class ChatListenerThread implements Runnable {

		Thread thread = null;

		public void start() {
			thread = new Thread(this);
			thread.setName("监听聊天线程");
			thread.start();
		}

		public void stop() {
			thread = null;
			for(ClientChatThread chatThread : chatWindowSocketList){
				chatThread.stop();
			}
			chatWindowSocketList.clear();
		}

		public void run() {
			ChatListener chatListener = createChatListener();
			try {
				while (null != thread && serverStartSuccess) {

					// 监听并获得聊天窗口socket
					Socket clientChatWindowSocket = chatSocket.accept();

					// 当监听到开启了一个聊天窗口后,启动线程不断的获得该窗口发出的消息,并做相应的转发和处理(即通过服务器中转聊天消息)
					ClientChatThread chatWindowThread = new ClientChatThread(clientChatWindowSocket, chatListener);
					LOG.debug("监听到打开了一个聊天窗口,开始启动窗口消息监听线程");
					chatWindowSocketList.add(chatWindowThread);
					chatWindowThread.start();
				}
			} catch (IOException e) {
				LOG.error(e.getMessage());
			} finally {
				closeServer();
			}
		}

	}

	
	/**
	 * @Description:  转发私聊消息
	 * @author guoyr
	 * @param chatThread
	 * @param bs
	 * @param sendId
	 * @param receiveId
	 */
	private void sendChatMessageAction(ClientChatThread chatThread, final byte[] bs, String sendId, String receiveId) {
		Date sendTime = new Date();
		
		//记录聊天消息
		chatThread.saveRecord(bs, sendTime);
		
		boolean isFind = false;
		// 从正在通过服务器聊天的窗口中找到接收者终端
		for (int i = 0; i < chatWindowSocketList.size(); i++) {
			try {
				final ClientChatThread client = (ClientChatThread) chatWindowSocketList.get(i);
				if (client == null) {
					continue;
				}
				// 如果在打开中的聊天线程中能找接收方正好是我,且发送方正好是对方
				if (receiveId.equals(client.getMyId()) && sendId.equals(client.getOtherId())) {
					isFind = true;
					
					int x = client.send(bs, bs.length);
					
					if (x == 0) { // 发送失败,就写入数据表
						chatThread.saveOfflineMessage(bs, sendTime);
					}
					break;
				}
			} catch (Exception ex) {
				LOG.error(ex.getMessage(), ex);
			}
		}
		
		// 没找到正在打开的聊天窗口则先写入数据表
		if(!isFind){
			chatThread.saveOfflineMessage(bs, sendTime);
			
			// 然后检查接收者是否在线,如果在线就让接收者的托盘闪动,以提示有新消息
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				String uid = cb.getMyid();
				if (uid == null || cb.getSocket() == null || cb.getIpAddress() == null){
					continue;
				}
				if (uid.equals(receiveId)) { // 若接收者在线就让他的托盘闪
					cb.sendToClient(IMConstants.CHAT + FENGEFU + sendId);
					break;
				}
			}
		}
	}
	
	/**
	 * @Description:  转发群组聊天消息
	 * @author guoyr
	 * @param chatThread
	 * @param bs
	 * @param sendId
	 * @param groupId
	 */
	private void sendChatGroupMessageAction(ClientChatThread chatThread, final byte[] bs, String sendId, String groupId) {
		Date sendTime = new Date();
		
		//记录聊天消息
		chatThread.writeGroupRecord(bs, groupId, sendTime);
		
		List<String> uList = new ArrayList<String>();
		QueryWrapper<GroupItem> queryWrapper = new QueryWrapper<GroupItem>();
		queryWrapper.lambda().select(GroupItem::getUserId).eq(GroupItem::getGroupId, groupId);
		List<Object> groupUsersId = groupItemService.listObjs(queryWrapper);
 
		if (null == groupUsersId) {
			groupUsersId = new ArrayList<Object>();
		}
		for (int i = 0; i < chatWindowSocketList.size(); i++) {
			final ClientChatThread c = chatWindowSocketList.get(i);
			if (c == null || c == chatThread || null == c.getGroupId()){
				continue;
			}

			if (null != groupUsersId && !groupUsersId.isEmpty()) {
				for (Object idObj : groupUsersId) {
					
					// 如果正好找到群成员打开的群聊天窗口
					if (idObj.equals(c.getMyId()) && groupId.equals(c.getGroupId())) {
						int x = c.send(bs, bs.length);
						
						// 发送成功就加入已发名单
						if (x == 1) { 
							uList.add(c.getMyId());
						}
					}
				}
			}
		}
		
		// 找出除自己外没有发送出去的群成员,并将信息存入数据库
		if (uList.size() < groupUsersId.size() - 1) {
			String msgId = chatThread.saveGroupOfflineMessage(bs, groupId, sendTime);
			if (null != msgId) {
				List<GroupMessage> groupMessageList = new ArrayList<GroupMessage>();
				for (Object idObj : groupUsersId) {
					
					// 去除已发送的和自己
					if (!uList.contains(idObj) && !idObj.equals(sendId)) {
						GroupMessage groupMessage = new GroupMessage();
						groupMessage.setId(IDUtils.getId());
						groupMessage.setGroupId(groupId);
						groupMessage.setMessageId(msgId);
						groupMessage.setReceiveId(idObj.toString());
						groupMessageList.add(groupMessage);
						for (int i = 0; i < clientBeanList.size(); i++) {
							ClientBean cb = clientBeanList.get(i);
							String uid = cb.getMyid();
							if (uid == null || cb.getSocket() == null)
								continue;
							if (uid.equals(sendId))
								continue;
							if (idObj.equals(uid)) { // 若接收者在线就让他的托盘闪
								cb.sendToClient("6," + groupId);
								break;
							}
						}
					}
				}
				groupMessageService.insertByBatch(groupMessageList);
			}
		}
	
	}
	
	
	/**
	 * @Description:  检查客户端是否在线
	 * @author guoyr
	 * @param uid
	 * @return
	 */
	private boolean containsClientList(String uid) {
		boolean isOnline = false;
		for (int i = 0; i < clientBeanList.size(); i++) {
			ClientBean cb = clientBeanList.get(i);
			if (cb.isFindUid(uid)) {
				isOnline = true;
				break;
			}
		}
		return isOnline;
	}

	// 检查客户端是否在线,若是异常掉线,就将他的在线状态由1修改为0,若在线列表有他,但状态却为0,就设为1
	private class CheckClientState extends Thread {
		private int countDays(String begin, String end) {
			int days = 0;
			DateFormat df = new SimpleDateFormat(DATE_FORMAT);
			Calendar c_b = Calendar.getInstance();
			Calendar c_e = Calendar.getInstance();
			try {
				c_b.setTime(df.parse(begin));
				c_e.setTime(df.parse(end));
				while (c_b.before(c_e)) {
					days++;
					c_b.add(Calendar.DAY_OF_YEAR, 1);
				}
			} catch (Exception ex) {
			}
			return days;
		}

		@Override
		public void run() {
			QueryWrapper<Employee> queryWrapper = new QueryWrapper<Employee>();
			queryWrapper.lambda().eq(Employee::getLineStatus,EmployeeEnum.ON_LINE);
			while (serverStartSuccess) {
				try {
					// 统计存在不在线的用户但状态是在线状态用户数
					int count = 0;
					List<Employee> onLineUserList = employeeService.list(queryWrapper);
					for (int i = 0; i < onLineUserList.size(); i++) {
						Employee user = (Employee) onLineUserList.get(i);
						try {
							if (!containsClientList(user.getId())) { // 当前在线列表中没发现此客户端ID
								user.setLineStatus(EmployeeEnum.OUT_LINE);
								employeeService.updateAssignProperty(user, new String[] { "lineStatus" });
								count ++;
								// LOG.error("客户端(uid=" + user.getUid() +
								// ")非法断线。通过服务器复位。", new Exception());
							}
						} catch (Exception ex) {
							LOG.error(ex.getMessage());
						}
					}
				
					if (count > 0) { // 通知所有在线用户刷新用户列表
						for (int c = 0; c < clientBeanList.size(); c++) {
							final ClientBean cb = clientBeanList.get(c);
							try {
								if (cb.getMyid() == null || cb.getSocket() == null){
									clientBeanList.remove(c);
									c--;
									continue;
								}
								cb.sendToClient("0,");
							} catch (Exception ex) {
								LOG.error(ex.getMessage());
							}
						}
					}
					// 清除重复的用户
					for (int i = 0; i < clientBeanList.size(); i++) {
						ClientBean cb = clientBeanList.get(i);
						if (cb == null || cb.getMyid() == null
								|| cb.getSocket() == null) {
							clientBeanList.remove(i);
							i--;
							continue;
						}
						for (int j = 0; j < clientBeanList.size(); j++) {
							if (i == j)
								continue;
							ClientBean cc = clientBeanList.get(j);
							if (cc == null || cc.getMyid() == null
									|| cc.getSocket() == null) {
								continue;
							}
							if (cb.getMyid().equals(cc.getMyid())) {
								if (i < j) {
									clientBeanList.remove(i);
									i--;
									break;
								} else {
									clientBeanList.remove(j);
									i--;
									break;
								}
							}
						}
					}
					
					Thread.sleep(CLEAR_SLEEP_TIME);
				} catch (Exception ex) {
					serverStartSuccess = false;
					LOG.error(ex.getMessage());
					closeServer();
				}
			}
		}
	}

	/**
	 * @Description: 关闭服务器启动的连接线监听程和聊天监听线程
	 * @author guoyr 
	 */
	public void closeServer() {
		serverStartSuccess = false;
		if (null != serverConnectionSocket) {
			try {
				serverConnectionSocket.close();
				serverConnectionSocket = null;
			} catch (IOException e) {
				System.err.println(e);
			}
		}
		
		if (null != chatSocket) {
			try {
				chatSocket.close();
				chatSocket = null;
			} catch (IOException e) {
			}
		}
		if (null != chatListenerThread) {
			chatListenerThread.stop();
		}
 	}

	/**
	 * @Description: 发送文件请求
	 * @author guoyr
	 * @param receiveId
	 * @param order 
	 */
	private void sendFileAction(String receiveId, String order) {
		try {
			ClientBean bean = null;
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				if (cb.isFindUid(receiveId)) {
					bean = cb;
					break;
				}
			}
			if (bean != null) {
				bean.sendToClient(order);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
	}

	/**
	 * @Description: 取消发送文件
	 * @author guoyr
	 * @param receiveId
	 * @param readStr 
	 */
	private void cancelSendFileAction(String receiveId, String readStr) {
		for (int i = 0; i < clientBeanList.size(); i++) {
			ClientBean cb = clientBeanList.get(i);
			if (cb.getMyid() == null || cb.getSocket() == null)
				continue;
			if (!cb.getMyid().equals(receiveId))
				continue;
			try {
				cb.sendToClient(readStr);
			} catch (Exception ex) {
				LOG.error("服务器转发(" + readStr + ")给客户端(" + receiveId + ")时异常:"
						+ ex.toString(), ex);
			}
			break;
		}
	}
	
	/**
	 * @Description: 发送离线文件请求
	 * @author guoyr
	 * @param receiveId
	 * @param order 
	 */
	private void sendOfflineFileRequestAction(String receiveId, String order) {
		try {
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				if (cb.isFindUid(receiveId)) {
					cb.sendToClient(order);
					break;
				}
			}
		} catch (Exception e) {
		}
	}

	
	/**
	 * @Description:  发送离线文件
	 * @author guoyr
	 * @param ip
	 * @param order
	 */
	private ServerFileThread sendOfflineFileAction(InetAddress ip, String order, ServerSendFileListener serverSendFileListener) {
		SendFileParam params = SendFileParam.getFileParams(order);
		ServerFileThread serverFileThread = new LixianWenJian(params, ip, serverSendFileListener, new SendFilter() {
			
			// 检查接收者是否在线,如果在线就通知接收离线文件
			public void checkAndSendOfflineFile(SendFileParam params) {
				for (int i = 0; i < clientBeanList.size(); i++) {
					ClientBean cb = clientBeanList.get(i);
					if (cb.isFindUid(params.getReceiveId())) {
						cb.sendOfflineFileFromServerToClientThread(params.getOrderStr());
						break;
					}
				}
			}
			// 告诉发送方,开始发送离线文件
			public void sendOfflineFileBegin(SendFileParam params){
				for (int i = 0; i < clientBeanList.size(); i++) {
					ClientBean cb = clientBeanList.get(i);
					if (cb.isFindUid(params.getReceiveId())) {
						cb.sendToClient(params.getOrderStr());
						break;
					}
				}
			}

		});
		serverFileThread.start();
		return serverFileThread;
	}

	private ServerFileThread sendFileByServerRequestAction(SendFileParam params, ServerSendFileListener serverSendFileListener){
		ServerFileThread serverFileThread = new SendFileByServerThread(params, serverSendFileListener, new SendFileByServerThread.SendFilter() {
			// 写入数据库后再看该用户在不在线,在线就通知个接收离线
			public void online(String fileName, String sendId, String receiveId, int port) {
//				for (int i = 0; i < clientList.size(); i++) {
//					ClientBean cb = clientList.get(i);
//					if (cb.isFindUid(receiveId)) {
//						cb.sendFileThread(fileName, sendId, receiveId);
//						// SendFileThread t = new SendFileThread(cb.getIp(),
//						// fileName, sendId, receiveId);
//						// threadVec.add(t);
//						// t.start();
//						break;
//					}
//				}
			}

			// // 告诉文件接收方,有服务器发送文件请求
			public void sendFileByServerRequest(SendFileParam params) {
				for (int i = 0; i < clientBeanList.size(); i++) {
					ClientBean cb = clientBeanList.get(i);
					if (cb.isFindUid(params.getReceiveId())) {
						cb.sendToClient(params.getOrderStr());
						break;
					}
				}
				
			}

		});
		serverFileThread.start();
		return serverFileThread;
	}
	
	/**
	 * @Description: 发送视频请求
	 * @author guoyr
	 * @param tuid
	 * @param readStr 
	 */
	private void sendVideoRequestAction(String tuid, String readStr) {
		try {
			ClientBean bean = null;
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				if (cb.isFindUid(tuid)) {
					bean = cb;
					break;
				}
			}
			if (bean != null) {
				bean.sendToClient(readStr);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
	}

	/**
	 * @Description: 接收视频
	 * @author guoyr
	 * @param receiveId
	 * @param readStr 
	 */
	private void accepVideoAction(String receiveId, String readStr) {
		try {
			ClientBean bean = null;
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				if (cb.isFindUid(receiveId)) {
					bean = cb;
					break;
				}
			}
			if (bean != null) {
				bean.sendToClient(readStr);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
	}

	/**
	 * @Description: 取消视频
	 * @author guoyr
	 * @param receiveId
	 * @param readStr 
	 */
	private void cancelVideoAction(String receiveId, String readStr) {
		for (int i = 0; i < clientBeanList.size(); i++) {
			ClientBean cb = clientBeanList.get(i);
			if (cb.getMyid() == null || cb.getSocket() == null)
				continue;
			if (!cb.getMyid().equals(receiveId))
				continue;
			try {
				cb.sendToClient(readStr);
			} catch (Exception ex) {
				LOG.error("服务器转发(" + readStr + ")给客户端(" + receiveId + ")时异常:"
						+ ex.toString(), ex);
			}
			break;
		}
	}

	/**
	 * @Description: 发送闪屏
	 * @author guoyr
	 * @param receiveId
	 * @param order 
	 */
	private void sendShanPingAction(String receiveId, String order) {
		try {
			ClientBean bean = null;
			for (int i = 0; i < clientBeanList.size(); i++) {
				ClientBean cb = clientBeanList.get(i);
				if (cb.isFindUid(receiveId)) {
					bean = cb;
					break;
				}
			}
			if (bean != null) {
				bean.sendToClient(order);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
	}
	/**
	 * @Description: 发送通知
	 * @author guoyr
	 * @param receiveId
	 * @param order 
	 */
	private void sendNoticeAction(String receiveId, String notice) {
		try {
			if(IMConstants.SYSTEM_NOTICE_ID.equals(receiveId)) {
				for (int i = 0; i < clientBeanList.size(); i++) {
					ClientBean cb = clientBeanList.get(i);
					if (cb.isFindUid(receiveId)) {
						cb.sendToClient(notice);
					}
				}
			}else {
				ClientBean bean = null;
				for (int i = 0; i < clientBeanList.size(); i++) {
					ClientBean cb = clientBeanList.get(i);
					if (cb.isFindUid(receiveId)) {
						bean = cb;
						break;
					}
				}
				if (bean != null) {
					bean.sendToClient(notice);
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
		}
	}

	/**
	 * @Description: 给除自己外的所有终端发送消息
	 * @author guoyr
	 * @param notice 
	 */
	private void sendCommondToAllClientAction(final String notice) {

		for (int i = 0; i < clientBeanList.size(); i++) {
			final ClientBean cb = clientBeanList.get(i);
			// 给除了自己外的所有终端发送消息
			if (cb.equals(this)){
				continue;
			}
			if (cb.getMyid() == null || cb.getSocket() == null){
				continue;
			}
			new Thread(new Runnable() { // 每个客户端启动一个线程给发通知
						public void run() {
							try {
								cb.sendToClient(notice);
							} catch (Exception ex) {
								LOG.error("服务器转发(" + notice + ")给客户端(" + cb.getMyid() + ")时异常:" + ex.toString(), ex);
							}
						}
					}).start();
		}

	}
	
	/**
	 * @Description: 给除自己外的所有终端发送消息
	 * @author guoyr
	 * @param notice 
	 */
	public void sendSystemNoticeAction(String noticeId, String notice) {
		sendSystemNoticeAction(noticeId, notice, null);
	}
	/**
	 * @Description: 给除自己外的所有终端发送消息
	 * @author guoyr
	 * @param notice 
	 */
	public void sendSystemNoticeAction(final String noticeId, final String notice, final String receiveIds) {
//		Date sendTime = new Date();
//		chatThread.writeNoticeRecord(bs, noticeId, sendTime);
		
		for (int i = 0; i < clientBeanList.size(); i++) {
			final ClientBean cb = clientBeanList.get(i);
			if (cb.getSocket() == null){
				continue;
			}
			// 如果指定了通知对象
			if(null != receiveIds && receiveIds.indexOf(cb.getMyid()) == -1) {
				continue;
			}
			new Thread(new Runnable() { // 每个客户端启动一个线程给发通知
				public void run() {
					
					try {
						String systemNotice = IMConstants.NOTICE.concat(ChatConstants.FENGEFU).concat(null != noticeId ? noticeId : "").concat(ChatConstants.FENGEFU).concat(notice).concat(ChatConstants.END_TAG);
						cb.sendToClient(systemNotice);
					} catch (Exception ex) {
						LOG.error("服务器转发(" + notice + ")给客户端(" + cb.getMyid() + ")时异常:" + ex.toString(), ex);
					}
				}
			}).start();
			
		}
	
	}

	// 先将服务器中所有此客户端的信息删除,再向此客户端发送信息,让它断线,全新登录
	private void reLoginAction(String uid) {
		try {
//			for (int i = 0; i < clientList.size(); i++) {
//				ClientBean cb = clientList.get(i);
//				if (cb != null && cb.isFindClient(uid, threadId)) {
//					cb.sendToServer(readStr);// 让客户端断线重新登录
//					clientList.remove(i);
//					i--;
//				}
//			}
			for (int i = 0; i < chatWindowSocketList.size(); i++) {
				ClientChatThread c = (ClientChatThread) chatWindowSocketList.get(i);
				if (c != null && c.getMyId() != null
						&& c.getMyId().equals(uid)) {
					chatWindowSocketList.remove(i);
					i--;
				}
			}
		} catch (Exception e) {
			LOG.error(e.toString(), e);
		}
	}

	private String getDateTime() {
		Calendar cdr = Calendar.getInstance();
		int yy = cdr.get(Calendar.YEAR);
		int mM = cdr.get(Calendar.MONTH) + 1;
		int dd = cdr.get(Calendar.DATE);
		int hh = cdr.get(Calendar.HOUR_OF_DAY);
		int mm = cdr.get(Calendar.MINUTE);
		int ss = cdr.get(Calendar.SECOND);
		String str = yy + "-" + mM + "-" + dd + " ";
		str += hh < 10 ? "0" + hh : "" + hh;
		str += ":";
		str += mm < 10 ? "0" + mm : mm;
		str += ":";
		str += ss < 10 ? "0" + ss : ss;
		return str;
	}

	
	/**
	 * @Description:  创建监听聊天线程
	 * @author guoyr
	 * @return
	 */
	private ChatListener createChatListener(){
		ChatListener chatListener = new ChatListener(){
			
			public void close(ClientChatThread chatThread) {
				chatWindowSocketList.remove(chatThread);
			}
			
			public void sendChatMessage(ClientChatThread chatThread , byte[] bs, String sendId, String receiveId) {
				sendChatMessageAction(chatThread, bs, sendId, receiveId);
			}
			
			public void sendGroupChatMessage(ClientChatThread chatThread, byte[] bs, String sendId, String groupId) {
				sendChatGroupMessageAction(chatThread, bs, sendId, groupId);
			}
			
			/**
			 * @Description: 发送通知
			 * @author guoyr
			 * @param chatThread
			 * @param bs
			 * @param sendId
			 * @param noticeId 
			 */
//			public void sendNoticeMessage(ClientChatThread chatThread, final byte[] bs, String sendId, String noticeId) {
//				sendNoticeAction(chatThread, bs, sendId, noticeId);
//			}
			
		};
		return chatListener;
	}
	/**
	 * @Description:  终端登录监听
	 * @author guoyr
	 */
	private ServerListener createClisConnectoinListener(){
		ServerListener clientListener = new ServerListener() {
			
			// 监听到该终端成功连接到服务器(即登录成功)
			public void connectionSuccess(ClientBean client){
				int x = clientBeanList.indexOf(client);
				if (x == -1) {
					clientBeanList.add(client);
//					while(true) {
//						try {
//							Thread.sleep(5000);
//							sendSystemNoticeAction(null, "refresh");
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
//					}
					
				} else {
					clientBeanList.set(x, client);
				}
				if(!useEmployee){
					QueryWrapper<Employee> queryWrapper = new QueryWrapper<Employee>();
					queryWrapper.lambda().select(Employee::getId).eq(Employee::getId,  client.getMyid());
		 
					Employee tempEmployee = employeeService.getOne(queryWrapper);
					if(null != tempEmployee){
						tempEmployee.setLineStatus(EmployeeEnum.ON_LINE);
 						employeeService.updateById(tempEmployee);
					}else {
 						tempEmployee = new Employee();
						tempEmployee.setId(client.getMyid());
						tempEmployee.setLineStatus(EmployeeEnum.ON_LINE);
						employeeService.save(tempEmployee);
					}
				}else {
					// 将该终端修改为在线状态
					UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<Employee>();
					updateWrapper.lambda().set(Employee::getLineStatus, EmployeeEnum.ON_LINE).eq(Employee::getId, client.getMyid());
					employeeService.update(updateWrapper);
				}
				
				// 在服务器后台输出当前在线人数
				if (null != serverInfoListener) {
					serverInfoListener.online(new Date(), client.getMyid(), clientBeanList.size());
				}
			}
			
			// 检查该终端是否已经登录
			public void checkLogin(String myId, int threadId){
				for(int i = 0; i < clientBeanList.size(); i++){
					ClientBean client = clientBeanList.get(i);
					// 如果在线的终端中存在该用户,但该登录线程!=已登录的线程,则认为该账号在其他电脑上登录了
					if(client.getMyid().equals(myId) && threadId != client.getThreadId()){
						
						// 告诉之前已经登录的终端,你已经在其他地方被登录,请重新登录
						client.sendToClient(IMConstants.RE_LOGIN_IN +FENGEFU+ client.getMyid());
						
						// 关闭之前登录的终端
						client.stop();
						i--;
						break;
					}
				}
			}
			
			// 有终端退出服务器
			public void quitOut(ClientBean client) {
				if(clientBeanList.contains(client)){
					if(!useEmployee){
						QueryWrapper<Employee> queryWrapper = new QueryWrapper<Employee>();
						queryWrapper.lambda().eq(Employee::getId,  client.getMyid());
						employeeService.remove(queryWrapper);
 					}else {
						// 修改该终端为离线状态
 						UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<Employee>();
 						updateWrapper.lambda().set(Employee::getLineStatus, EmployeeEnum.ON_LINE).eq(Employee::getId, client.getMyid());
						employeeService.update(updateWrapper);
					}
					
					// 移除该终端
					clientBeanList.remove(client);
					if (null != serverInfoListener) {
						serverInfoListener.offline(new Date(), client.getMyid(), clientBeanList.size());
					}
				}
			}

			// 发送文件请求
			public void sendFileRequest(String receiveId, String order) {
				sendFileAction(receiveId, order);
			}
			// 通过服务器转发文件请求
			public ServerFileThread sendFileByServerRequest(SendFileParam params, ServerSendFileListener serverSendFileListener){
				return sendFileByServerRequestAction(params, serverSendFileListener);
			}
			// 取消文件发送
			public void cancelSendFile(String receiveId, String order) {
				cancelSendFileAction(receiveId, order);
			}

			// 发送离线文件请求
			public void sendOfflineFileRequest(String receiveId, String order) {
				sendOfflineFileRequestAction(receiveId, order);
			}

			// 发送离线文件
			public ServerFileThread sendOfflineFile(InetAddress ip, String order, ServerSendFileListener serverSendFileListene) {
				order += FG + serverIp;
				return sendOfflineFileAction(ip, order, serverSendFileListene);
				// new LixianWenJian(order, ip).start();
			}

			// 发送视频请求
			public void sendVideoRequest(String receiveId, String order) {
				sendVideoRequestAction(receiveId, order);
			}

			// 接收视频
			public void receiveVideo(String receiveId, String order) {
				accepVideoAction(receiveId, order);
			}

			// 取消视频
			public void cancelVideo(String receiveId, String order) {
				cancelVideoAction(receiveId, order);
			}

			// 发送闪屏
			public void sendShanPing(String receiveId, String order) {
				sendShanPingAction(receiveId, order);
			}

			// 让客户端断线并重新登录
			public void reLogin(String myId) {
				reLoginAction(myId);
			}

			// 给所有终端发送消息
			public void sendCommondToAllClient(String notice) {
				sendCommondToAllClientAction(notice);
			}

			@Override
			public void sendNotice(String receiveId, String notice) {
				sendNoticeAction(receiveId, notice);
			}
		};
		return clientListener;
	}
}