基于udp通信协议开发的简易聊天系统1.0分析

访客 阅读:174 2021-09-05 18:21:16 评论:0
本文章主要介绍了基于udp通信协议开发的简易聊天系统1.0,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!

最近闲来没事,由于工作环境异常恶劣,项目组同事之间进行交流只能通过email感觉非常麻烦,而且沟通不是很及时,所以就想着自己写个局域网的聊天工具玩玩!在javaeye潜水已经很长时间了,该贴可以说是真正的处女贴,哈哈,废话不多,直接上源码,喜欢的朋友可以拷贝下,自己扩展些功能。。。
 

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.GridLayout; 
import java.awt.Panel; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.awt.event.WindowEvent; 
import java.awt.event.WindowListener; 
import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.DatagramSocket; 
import java.net.InetAddress; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.TreeMap; 
 
import javax.swing.JButton; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JTextArea; 
import javax.swing.JTextField; 
 
 
/** 
 * 主窗体 
 * @author yKF42330 
 * 
 */ 
public class MainFrame extends JFrame{ 
	//online user 
	Map<String,String> userMap=new TreeMap<String,String>(); 
	//聊天内容 
	Map<String,String> contentMap=new HashMap<String, String>(); 
	//上、下部分面板 
	Panel upPanel,downPanel; 
	//文本输入框 
	JTextField ipTextField,dataTextField; 
	//聊天内容窗口 
	JTextArea contextTextArea; 
	//用户下拉框 
	JComboBox userComboBox; 
	//发送按钮 
	JButton sendButton; 
	//udp发送信息 
	DatagramSocket sendsocket=null; 
	DatagramSocket revicesocket=null; 
	DatagramSocket senduser=null; 
	DatagramSocket reviceuser=null; 
	DatagramPacket dp=null; 
	public MainFrame (){ 
		super(); 
	} 
	 
	public MainFrame (String title){ 
		super(title); 
		setDefaultCloseOperation(EXIT_ON_CLOSE); 
		setVisible(true); 
	}
	 
	public MainFrame (String title,int w,int h,Component c){ 
		super(title); 
		setSize(w, h); 
		setDefaultCloseOperation(EXIT_ON_CLOSE); 
		setLocationRelativeTo(c); 
		display(); 
		setVisible(true); 
	} 
	/** 
	 * 用户发送通知 
	 * @param type 通知类型 add,delete 
	 */ 
	public void sendUserInfo(final String type){ 
		new Thread(new Runnable() { 
			@Override 
			public void run() { 
				while(true){ 
					try { 
						if(InetAddress.getLocalHost()==null){ 
							JOptionPane.showMessageDialog(null, "对不起,您的网络环境有问题!"); 
							return; 
						} 
						String [] strs=InetAddress.getLocalHost().toString().split("/"); 
						senduser=new DatagramSocket(); 
						DatagramPacket dp=new DatagramPacket((type+"/"+strs[0]+"/"+strs[1]).getBytes(), (type+"/"+strs[0]+"/"+strs[1]).getBytes().length,InetAddress.getByName("255.255.255.255"),4000); 
						if(!senduser.isClosed()) 
							senduser.send(dp); 
					} catch (Exception e1) { 
						e1.printStackTrace(); 
					}finally{ 
						senduser.close(); 
					} 
				} 
			} 
		}).start(); 
	} 
	//监听在线用户信息 
	public void receiveUsers(){ 
		new Thread(new Runnable() { 
			@Override 
			public void run() { 
				while(true){ 
					try { 
						reviceuser=new DatagramSocket(4000); 
						byte [] str=new byte[1024*1024]; 
						DatagramPacket revicedp=new DatagramPacket(str, str.length); 
						reviceuser.receive(revicedp); 
						String data=new String(revicedp.getData()); 
						String [] datas=data.split("/"); 
						if(datas[0].equals("add")&&!userMap.containsValue(datas[2].trim())){ 
							userMap.put(datas[1].trim(), datas[2].trim()); 
							userComboBox.addItem(datas[1].trim()); 
						} 
						else if(datas[0].equals("delete")&&userMap.containsValue(datas[2].trim())){ 
							userMap.remove(datas[1].trim()); 
							userComboBox.removeItem(datas[1].trim());	 
						} 
								 
					} catch (IOException e) { 
						e.printStackTrace(); 
					}finally{ 
						reviceuser.close(); 
					} 
				} 
			} 
		}).start(); 
	} 
	//发送message 
	public void sendMessage(){ 
		String str=dataTextField.getText(); 
		if(str==null||str.equals("")){ 
			JOptionPane.showMessageDialog(null,"请输入内容!"); 
			return; 
		} 
		try { 
			sendsocket=new DatagramSocket(); 
			DatagramPacket senddp=new DatagramPacket(str.getBytes(), str.getBytes().length,InetAddress.getByName((String)userComboBox.getSelectedItem()),3000); 
			sendsocket.send(senddp); 
			contextTextArea.append("\n本机:"+str); 
		} catch (Exception e1) { 
			e1.printStackTrace(); 
		}finally{ 
			sendsocket.close(); 
		} 
		dataTextField.setText(""); 
	} 
	//接收message 
	public void receiveMessage(){ 
		//接收信息 
		new Thread(new Runnable() { 
			@Override 
			public void run() { 
				while(true){ 
					try { 
						revicesocket=new DatagramSocket(3000); 
						byte [] str=new byte[1024]; 
						DatagramPacket revicedp=new DatagramPacket(str, str.length);  
						revicesocket.receive(revicedp); 
						contextTextArea.append("\n"+revicedp.getAddress().getHostAddress()+":"+new String(revicedp.getData())); 
					} catch (IOException e) { 
						e.printStackTrace(); 
					}finally{ 
						revicesocket.close(); 
					} 
					 
				} 
			} 
		}).start(); 
	}
private void display (){ 
		try { 
			String [] host=InetAddress.getLocalHost().toString().split("/"); 
			userMap.put(host[0],host[1]); 
		} catch (Exception e1) { 
			e1.printStackTrace(); 
		} 
		addWindowListener(new WindowListener() { 
			@Override 
			public void windowOpened(WindowEvent e) {} 
			@Override 
			public void windowIconified(WindowEvent e) {} 
			@Override 
			public void windowDeiconified(WindowEvent e) {} 
			@Override 
			public void windowDeactivated(WindowEvent e) {} 
			@Override 
			public void windowClosing(WindowEvent e) { 
				sendUserInfo("delete"); 
			} 
			@Override 
			public void windowClosed(WindowEvent e) {} 
			@Override 
			public void windowActivated(WindowEvent e) {} 
		}); 
		sendButton=new JButton("send"); 
		//按钮单击事件 
		sendButton.addActionListener(new ActionListener() { 
			@Override 
			public void actionPerformed(ActionEvent e) { 
				sendMessage(); 
			} 
		}); 
		contextTextArea=new JTextArea(); 
		ipTextField=new JTextField("请输入ip地址"); 
		dataTextField=new JTextField(); 
		//添加回车响应事件 
		dataTextField.addKeyListener(new KeyListener() { 
			@Override 
			public void keyTyped(KeyEvent e) {} 
			@Override 
			public void keyReleased(KeyEvent e) {} 
			@Override 
			public void keyPressed(KeyEvent e) { 
				if(e.getKeyCode()==KeyEvent.VK_ENTER){ 
					sendMessage(); 
				} 
			} 
		}); 
		 //像在线用户发送上线通知 
		sendUserInfo("add"); 
		userComboBox=new JComboBox(userMap.keySet().toArray()); 
		//接收信息 
		receiveMessage(); 
		//监听在线用户信息 
		receiveUsers(); 
		downPanel=new Panel(new GridLayout(1,3)); 
		downPanel.add(userComboBox); 
		downPanel.add(dataTextField); 
		downPanel.add(sendButton); 
		setLayout(new BorderLayout()); 
		add(downPanel,BorderLayout.SOUTH); 
	    add(contextTextArea,BorderLayout.CENTER); 
	} 
	 
	public static void main(String[] args) { 
		new MainFrame("简易聊天系统1.0",500,350,null); 
	} 
}

标签:java
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号