JAVA:使用UDP网络编程,实现简单的聊天窗口

使用技术
java Swing插件(界面可进行拖拽实现) socket套接字 多线程(runnable)
关于swing
首先去网上下载一个swing的插件,在eclipse中help中有install new software中进行插件的安装
后台数据交互的代码

import java.io.IOException;
import java.net.DatagramPacket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 实现runable接口
 * @author mine
 *
 */
public class Recv  implements Runnable {
	@Override
	public void run() {
		while(true){
			byte[] buf=new byte[1024];
			DatagramPacket dp=new DatagramPacket(buf, 1024);//使用 DatagramPacket() 创建要发送的数据包
			
				try {
					Chat.getSocket().receive(dp);//从chat中获取数据

					String str=new String(dp.getData(),0,dp.getLength());//获取时间和数据的长度
					String ip=dp.getAddress().getHostAddress();//获取到IP地址
					int port =dp.getPort();//获取到端口号
					Date now=new Date();
					DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//规定日期格式
					String strnow =df.format(now);//获取到当前日期
					String newmsg=ip+":"+port+""+strnow +"说"+str;//显示ip port strnow等新消息
					String oldmsg=Chat.getTextMsg().getText();//原来的消息
					String msg =newmsg +"\r\n"+oldmsg;//需要显示的信息(新旧消息都会显示到窗口中)
					Chat.getTextMsg().setText(msg);//将信息显示到窗口中
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
}

这儿是前端得代码,界面布局的代码是由swing自动生成
数据交互还有点击事件还是需要自己动手敲得



import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingConstants;

import edu.day17.Class.ThreadTest1;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Chat extends JFrame {

	private JPanel contentPane;
	private JTextField textid;
	private JTextField textport;
	private JTextField textSend;
	private static JTextArea textMsg;
	
	public static JTextArea getTextMsg() {
		return textMsg;
	}

	private static DatagramSocket socket;
	public static DatagramSocket getSocket() {
		return socket;
	}
	

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		
		EventQueue.invokeLater(new Runnable(){
			public void run() {
				try {
					Chat frame = new Chat();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
	}

	/**
	 * Create the frame.
	 */
	public Chat() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 906, 440);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(22, 9, 612, 221);
		contentPane.add(scrollPane);
		
		textMsg = new JTextArea();
		scrollPane.setViewportView(textMsg);
		
		JLabel lblNewLabel = new JLabel("ip");
		lblNewLabel.setBounds(20, 256, 72, 18);
		contentPane.add(lblNewLabel);
		
		textid = new JTextField();
		textid.setBounds(66, 253, 86, 24);
		contentPane.add(textid);
		textid.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("\u7AEF\u53E3\u53F7");
		lblNewLabel_1.setBounds(277, 255, 72, 18);
		contentPane.add(lblNewLabel_1);
		
		textport = new JTextField();
		textport.setBounds(383, 251, 86, 24);
		contentPane.add(textport);
		textport.setColumns(10);
		
		textSend = new JTextField();
		textSend.setBounds(22, 287, 705, 93);
		contentPane.add(textSend);
		textSend.setColumns(10);
		
		JButton button = new JButton("send");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				String ip=textid.getText();//获取IP
				int port =Integer.parseInt(textport.getText());//接口定义
				String sendmsg=textSend.getText();//接受发送的消息
				byte[] buf=sendmsg.getBytes();//将数组转化为byte格式
				try {
					//使用 DatagramPacket() 创建要发送的数据包(消息数据,长度,ip地址,端口号)
					DatagramPacket dp=new DatagramPacket(buf, buf.length,InetAddress.getByName(ip),port);
					socket.send(dp);//通过套接字将数据包发送出去
					//System.out.println(socket.getPort());
					textSend.setText("");//将输入框制空
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		button.setBounds(761, 320, 113, 27);
		contentPane.add(button);
		
		try {
			/**
			 * 创建线程和端口号
			 */
			socket=new DatagramSocket(8888);
			Thread th=new Thread(new Recv());
			th.start();
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

效果大概这个样子
JAVA:使用UDP网络编程,实现简单的聊天窗口_第1张图片
一个简单的聊天工具就over了

你可能感兴趣的:(java)