Java基于UDP用Socket实现点对点聊天

核心代码比较简单,基于UDP的聊天实现,采用读,写分离,用不同的线程实现。


主要实现类为

DatagramSocket()与DatagramPacket(),默认端口为8009,Ip地址需要自己输入。

Reader线程:

package com.java.gui;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Reader {
	private  DatagramSocket ds = null;
	private  DatagramPacket dp  = null;
	//private String string = null;
	
	public void run()
	{
		byte reader[] = new byte[1024];

		try {
			ds = new DatagramSocket(8009);
			dp = new DatagramPacket(reader, 1024);
			String jieshou = null;
			ds.receive(dp);
			jieshou = new String(dp.getData(), 0, dp.getLength());
			System.out.println(jieshou);
			app1.fanhui = jieshou;
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			if(ds != null)
			{
				ds.close();
			}
		}
	}

	
	
}
Writer线程:

package com.java.gui;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Write extends Thread{

	private String string = null;
	private String address = null;
	public Write(String string, String address)
	{
		this.address = address;
		this.string = string;
	}
	
	public void run()
	{
		DatagramSocket ds = null;
		DatagramPacket dp = null;
		//byte write[] = new byte[1024];
		try {
			//设置目标主机
			ds = new DatagramSocket();	
//			byte test[] = null;
//			test = string.getBytes();		
			dp = new DatagramPacket(string.getBytes(), string.getBytes().length, InetAddress.getByName(address),8009);
			
			//发送消息
			ds.send(dp);
			ds.close();
			
			System.out.println("成功发送!");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

下面是界面代码,用到了windowBuilder插件:


package com.java.gui;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class app1 {
	
	static String fanhui =null;
	private static String address = null;
	private JFrame frmTest;
	private JTextField textField;
	private static JTextArea textArea;
	private static Date date = null;
	/**
	 * Launch the application.
	 */
	

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					
					app1 window = new app1();
					window.frmTest.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		while(true)
		{
			new Reader().run();
			if(fanhui != null)
			{
				SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
				date = new Date();
				String form = null;
				form = format.format(date);
				textArea.append("from"+address+" ("+form+") "+ ":\n"+"  "+fanhui+"\n");
			}
		}
		
	}

	/**
	 * Create the application.
	 */
	public app1() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmTest = new JFrame();
		frmTest.setTitle("test");
		frmTest.setBounds(100, 100, 492, 391);
		frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmTest.getContentPane().setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 10, 261, 202);
		frmTest.getContentPane().add(scrollPane);
		
		textArea = new JTextArea();
		textArea.setLineWrap(true);
		textArea.setEditable(false);
		textArea.setColumns(20);
		scrollPane.setViewportView(textArea);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(10, 225, 261, 86);
		frmTest.getContentPane().add(scrollPane_1);
		
		JTextArea textArea_1 = new JTextArea();
		scrollPane_1.setViewportView(textArea_1);
		
		JButton button = new JButton("\u53D1\u9001");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				//监听发送按钮
				String string = null;
				string = textArea_1.getText();
				if(address == null)
				{
					JOptionPane.showMessageDialog(frmTest, "主机号为空!", "提示" , JOptionPane.INFORMATION_MESSAGE);
					textArea_1.setText("");
				}
				else if( !(string.equals("")) && string != null )
				{
					SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
					date = new Date();
					String form = null;
					form = format.format(date);
					new Write(string, address).start();
					textArea.append("from"+address+" ("+form+") "+ ":\n"+"  "+string+"\n");
					textArea_1.setText("");
				}
				else
				{
					JOptionPane.showMessageDialog(frmTest, "发送内容不能空!", "提示" , JOptionPane.INFORMATION_MESSAGE);
				}
				//textArea.setText(string);
			}
		});
		button.setBounds(295, 288, 93, 23);
		frmTest.getContentPane().add(button);
		
		JLabel lblTest = new JLabel("\u672A\u8FDE\u63A5");
		lblTest.setHorizontalAlignment(SwingConstants.CENTER);
		lblTest.setBounds(328, 178, 93, 23);
		frmTest.getContentPane().add(lblTest);
		
		textField = new JTextField();
		textField.setBounds(295, 97, 171, 23);
		frmTest.getContentPane().add(textField);
		textField.setColumns(10);
		
		JButton btnNewButton = new JButton("\u8FDE\u63A5\u4E3B\u673A");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				//监听IP地址输入按钮
				String string = textField.getText();
				if(string == null)
				{
					JOptionPane.showMessageDialog(frmTest, "主机号为空!", "提示" , JOptionPane.INFORMATION_MESSAGE);
				}
				else if((string.matches("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$") == false))
				{
					JOptionPane.showMessageDialog(frmTest, "Ip地址格式错误!!", "提示" , JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					lblTest.setText("连接成功!");
					address = string;
				}
			}
		});
		btnNewButton.setBounds(328, 138, 93, 23);
		frmTest.getContentPane().add(btnNewButton);
	}

}

以下为界面图片:

Java基于UDP用Socket实现点对点聊天_第1张图片
下面是执行图片,由于在本机测试,所以会有重复出现的内容,即自己发送显示一遍,接收显示一遍

Java基于UDP用Socket实现点对点聊天_第2张图片

你可能感兴趣的:(Java基础)