⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chatdog.java

📁 java简易在线聊天程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
		LocalIP=InetAddress.getLocalHost().getHostAddress();
		System.out.println("System-getLocalIP:"+LocalIP);
		//getLIP.close();
		nClient=null;
		System.out.println("Port Open:"+REMOTE_PORT);
		while(true){
			try{
				nClient=serverSock.accept();
				System.out.println("Server Socket:OneClient Accept!");
				(new Thread(){
					public void run(){
						dealMessageReceive(nClient);
					}
				}).start();
			
			}catch(Exception e){System.out.println(e.getMessage());}
		}
	}
	public void dealMessageReceive(Socket client){
		try{		
			BufferedReader sbfr=null;
			PrintStream spw=null;
			String msg=null;
			sbfr=new BufferedReader(new InputStreamReader(client.getInputStream()));
			spw=new PrintStream(client.getOutputStream());
			msg=sbfr.readLine();
			System.out.println("ServerSocket get head message(from:"+client.getInetAddress().getHostAddress()+"):"+msg);
			if(msg.equals(MSG_CHAT)){
				chatMessageReceive(new String(sbfr.readLine()),new String(sbfr.readLine()),new String(sbfr.readLine())
				                   ,new String(client.getInetAddress().getHostAddress()));
				System.out.println(client.getInetAddress().getHostAddress());
			}
			else if(msg.equals(MSG_ISONLINE)){
				spw.println(MSG_IAMONLINE+ENTER_CHAR+user);
			}else if(msg.equals(MSG_ADDFRIEND)){
				System.out.println("System:Begin deal MSG_ADDFRIEND");
				//System.out.println("System:Check info read by Socket:"+sbfr.readLine());
				//System.out.println("System:Check info read by Socket:"+sbfr.readLine());
				addFriendMessageReceive(new String(sbfr.readLine()),new String(sbfr.readLine()),new String(client.getInetAddress().getHostAddress()));
				System.out.println("System:Complete deal MSG_ADDFRIEND");
			}else if(msg.equals(MSG_REFUSEADD)){
				(new JOptionPane()).showMessageDialog(null,new JLabel(sbfr.readLine()+"("+sbfr.readLine()+")"
				                                                     +"拒绝了你的添加好友请求"),
			                                          "拒绝请求",JOptionPane.INFORMATION_MESSAGE);
			}else if(msg.equals(MSG_ACCEPTADD)){
				String name=sbfr.readLine(),IP=sbfr.readLine();
				(new JOptionPane()).showMessageDialog(null,new JLabel(name+"("+IP+")"
				                                                     +"接受了你的添加好友请求"),
			                                          "接受请求",JOptionPane.INFORMATION_MESSAGE);
			    addFriend(name,IP,client.getPort());
			    //sortFriend();
			    mg.showGUI(friend,friendNum);
			}else if(msg.equals(MSG_NOTHIME)){
				String name=sbfr.readLine(),IP=sbfr.readLine();
				(new JOptionPane()).showMessageDialog(null,new JLabel(name+"("+IP+")"
				                                                     +"拒绝了你的添加好友请求"),
			                                          "拒绝请求",JOptionPane.INFORMATION_MESSAGE);
				
			}
		}catch(Exception e){System.out.println(e.getMessage());}
		try{client.close();}catch(Exception e){}
	}
	private void chatMessageReceive(String hostName,String postName,String msg,String IP){
		int fID=0;
		String rmsg=msg.replaceAll(ENTER_REPLACE_CHAR,ENTER_CHAR);
		synchronized(friendLock){
		while(fID<=friendNum&&(!friend[fID].IP.equals(IP)||!friend[fID].name.equals(postName))) fID++;
			if(fID<=friendNum){
				friend[fID].chatNote=friend[fID].chatNote+ENTER_CHAR+friend[fID].name+":"+rmsg;
				if(friend[fID].chatWindow==null) ((friend[fID].chatWindow=new chatGUI(friend[fID],user))).showGUI();
				else friend[fID].chatWindow.showGUI();
			}
			else{
				/*
			 	*
			 	*here is how to deal when Stranger comes
			 	*
				 *and I have not get an idea how to do it
			 	*
			 	*
			 	*/
			}
		}
		
	}
	/*
	 *
	 *
	 *      USE SOCKET(AND ONLY SEND)
	 *
	 *
	 */
	private void addFriendMessageReceive(String hostName,String postName,String IPPost){
		System.out.println("System:addFriendMessagereceive:"+IPPost+postName+","+hostName);	
		int port;
		port=getPort(postName,IPPost);
		if(port==-1) return;
		if(!hostName.equals(user)) {
			try{sendMessage(MSG_NOTHIME+ENTER_CHAR+hostName+ENTER_CHAR+LocalIP,IPPost,port);}catch(Exception e){}
			return;
		}
		int choice;
		choice=(new JOptionPane()).showConfirmDialog(null,
		            new JLabel(postName+"(IP:"+IPPost+")"+"想添加你为好友,你接受请求吗?"),"添加好友",
		            JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
		try{            
			if(choice==JOptionPane.NO_OPTION){
				sendMessage(MSG_REFUSEADD+ENTER_CHAR+hostName+ENTER_CHAR+LocalIP,IPPost,port);
			}else{
				sendMessage(MSG_ACCEPTADD+ENTER_CHAR+hostName+ENTER_CHAR+LocalIP,IPPost,port);
				if(!isFriendExist(postName,IPPost)){
					choice=(new JOptionPane()).showConfirmDialog(null,
		            	new JLabel("你也想加对方为好友吗?"),"添加好友",
		            	JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);
		    		if(choice==JOptionPane.YES_OPTION)  {
		    			addFriend(postName,IPPost,port);
		    			//sortFriend();
		    			mg.showGUI(friend,friendNum);
		    		}
		    	}
		   
			}
		}catch(Exception e){
			System.out.println("System-add-Friend-Exception:"+e.toString());
			(new JOptionPane()).showMessageDialog(null,new JLabel("对方可能已经不在线了,添加失败"),
			                                      "添加失败",JOptionPane.INFORMATION_MESSAGE);
		}
	}
	/*
	 *
	 *       USE SOCKET
	 *
	 *
	 */
	private boolean tryAddFriend(String name,String IP){
		Socket sock;
		//BufferedReader sbfr=null;
		PrintStream spw=null;
		int tryPort=SERVER_PORT;
		boolean checkEnd=false;
		while(tryPort<=MAX_PORTNUM*PORT_DELTA+SERVER_PORT){
			try{
				System.out.println("System-try addFriend():"+name+" "+IP+":"+tryPort);
				sock=new Socket(IP,tryPort);
				spw=new PrintStream(sock.getOutputStream());
				spw.println(MSG_ADDFRIEND+ENTER_CHAR+name+ENTER_CHAR+user);
				System.out.println("Client(Socket):"+MSG_ADDFRIEND+ENTER_CHAR+user+ENTER_CHAR+LocalIP);
				checkEnd=true;
				try{sock.close();}catch(Exception e){}
			}catch(Exception e){
				System.out.println(e.getMessage());
				//tryPort+=PORT_DELTA;
			}
			tryPort+=PORT_DELTA;
		}
		
		return checkEnd;
	}
	private boolean isFriendExist(String name,String IP){
		int fn;
		synchronized(friendLock){
			fn=friendNum;
		}
		for(int i=0;i<=fn-1;i++)
		 if(friend[i].name.equals(name)&&friend[i].IP.equals(IP)) return true;
		return false;
	}
	private void addFriend(String name,String IP,int port){
		int fn;
		//try{
		synchronized(friendLock){
			friendNum++;
			fn=friendNum;
		}
		friend[fn-1]=new Friend(name,IP,"head.jpg");
		friend[fn-1].port=port;
		friend[fn-1].setIsOnline(true);
		friend[fn-1].setActionCommand(""+(fn-1));
		friend[fn-1].addActionListener(this);
		//}catch(Exception e){System.out.println("System-addFriend(Exception):"+e.getMessage());		}
		try{saveFile();}catch(Exception e){System.out.println("System-saveFile:"+e.getMessage());}
		System.out.println("System-addFriend:"+name+","+IP+" Complete!");
	}
	private void delFriend(){
		System.out.println("System-delFriend:begin......");
		synchronized(friendLock){
			int e=friendNum-1,p=0,delta=0;
			while(p<=e){
				if(!dfGUI.isFriendSelect(p)) delta++;
				if(p-delta>=0) friend[p-delta]=friend[p].clone();
				p++;
			}
			friendNum=friendNum-delta;
		}
		try{saveFile();}catch(Exception e){}
		
		System.out.println("System-delFriend:Complete!--:friendNum:"+friendNum);
	}
	
	private void initMainGUI(){
		mg=new mainGUI(user);
		mg.addFriend.addActionListener(this);
		mg.delFriend.addActionListener(this);
		mg.showGUI(friend,friendNum);
	}
	
	
	private void initAFGUI(){
		afGUI=new addFriendGUI(mg.addFriend);
		afGUI.btnAddFriendOK.addActionListener(this);
	}
	
	private void initDFGUI(){
		dfGUI=new delFriendGUI(mg.delFriend);
		dfGUI.btnDelFriendOK.addActionListener(this);
	}
	public void begin(){
		
		try{logon();} catch(Exception e){System.out.println(e.getMessage());}
		(new Thread(){
			public void run(){
				while(true){
					checkFriend();
					//sortFriend();
					//if(mg!=null)mg.showGUI(friend,friendNum);
					try{Thread.sleep(10000);}catch (Exception e){}
				}
			}
		}).start();
		
		initMainGUI();
		initAFGUI();
		initDFGUI();
		try{openPort();}catch(Exception e){}
		
	}
	public void exit()throws IOException{
		if(fr!=null)fr.close();
		if(fw!=null)fw.close();
	}
	
	
	public void run(){
	}
	public void actionPerformed(ActionEvent e){
		String actionCommandStr=e.getActionCommand();
		if(actionCommandStr.equals(BTN_ADDFRIEND)){
			new Thread(){
				public void run(){
					System.out.println("BTN_ADDFRien Thread Start");
					afGUI.setMessage("");
					afGUI.setVisible(true);
					mg.addFriend.setEnabled(false);
				}
			}.start();
			System.out.println(BTN_ADDFRIEND);
		}
		else if(actionCommandStr.equals(BTN_DELFRIEND)){
			dfGUI.showGUI(friend,friendNum);
			System.out.println("System-BTN_DELFRIEND:friendNum:"+friendNum);
		}
		else if(actionCommandStr.equals(BTN_ADDFRIENDOK)){
			if(afGUI.getName().equals("")||afGUI.getIP().equals("")){
				afGUI.setMessage("请填写完整的客户信息!");
			}else if(isFriendExist(afGUI.getName(),afGUI.getIP())){
				(new JOptionPane()).showMessageDialog(null,new JLabel("改用户已经被加为好友"),
			                                          "好友已经存在",JOptionPane.INFORMATION_MESSAGE);
			}else if(!tryAddFriend(afGUI.getName(),afGUI.getIP())){
				afGUI.setMessage("对方不在线,添加好友失败");
			} else{
				/*(new JOptionPane()).showMessageDialog(afGUI,new JLabel("添加好友成功"),
			                                      "成功",JOptionPane.INFORMATION_MESSAGE);*/
			    afGUI.setMessage("消息已成功发送,你可以继续添加其他好友");
			}
			mg.addFriend.setEnabled(true);
		}
		else if(actionCommandStr.equals(BTN_DELFRIENDOK)){
			System.out.println("System-BTN Evtion:BTN_DELFRIENDOK");
			delFriend();
			try{Thread.sleep(50);}catch(Exception ee){}
			//sortFriend();
			
		    mg.showGUI(friend,friendNum);
			
			dfGUI.showGUI(friend,friendNum);
			
		}
		else{
			activeFriendID=Integer.parseInt(actionCommandStr);
			Thread newChatWindow=new Thread(){
				public void run(){
					if(!friend[activeFriendID].isWindowShow){
				  	(friend[activeFriendID].chatWindow=new chatGUI(friend[activeFriendID],user)).showGUI();
				}
			}
			};
			newChatWindow.start();
		}
	}
	public void sendMessage(String msg,String IP,int port) throws Exception{
		Socket sock=new Socket(IP,port);
		PrintStream sps=new PrintStream(sock.getOutputStream());
		sps.println(msg);
		System.out.println("S-Socket/ServerSocket-send:"+IP+":"+port+": "+msg);
		sps.close();
		sock.close();
	}
	
	public void windowClosing(WindowEvent e){
		mg.addFriend.setEnabled(true);
	}
	public static void main(String args[]){
		ChatDog chatdog=new ChatDog();
		chatdog.begin(); 
	}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -