论坛首页 Java企业应用论坛

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

浏览 8420 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (1) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-12-19   最后修改:2011-12-21
      最近闲来没事,由于工作环境异常恶劣,项目组同事之间进行交流只能通过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);
	}
   发表时间:2011-12-19   最后修改:2011-12-21
	
	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();
	}
0 请登录后投票
   发表时间:2011-12-19   最后修改:2011-12-21
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);
	}
}
0 请登录后投票
   发表时间:2011-12-20  
亏你说在iteyey潜水很长时间,代码用/[code/] 包裹都不知道呀
0 请登录后投票
   发表时间:2011-12-20  
log4j_properties 写道
亏你说在iteyey潜水很长时间,代码用/[code/] 包裹都不知道呀

一针见血!
0 请登录后投票
   发表时间:2011-12-20  
扩展,估计也用不上这个吧。
0 请登录后投票
   发表时间:2011-12-21   最后修改:2011-12-21
 
哈哈
0 请登录后投票
   发表时间:2011-12-21  
确实很简易
0 请登录后投票
   发表时间:2011-12-21  
月经贴!
0 请登录后投票
   发表时间:2011-12-21  
这是最基本的UDP吧,建议用NIO或AIO
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics