java swing socket多人聊天项目

  1. 使用Eclipse的windows builder插件设计界面。
  2. 使用socket和多线程实现聊天的功能,建立了两个内部类,分别实现了Runnable接口。
  3. 聊天面板采用了JTextPane,发送信息为红色,接受信息为蓝色,并设为不可编辑。
  4. “开始”按钮开启接受线程,“发送”按钮开启发送线程。
  5. 在发送框中输入“exit”,关闭接受线程。

注意:JTextPane要写在构造方法外并初始化 ,否则不能改变JTextPane的内容。

private JTextPane textPane = new JTextPane();

 

java swing socket多人聊天项目_第1张图片

 

 

package basic;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.TextArea;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.xml.stream.events.StartDocument;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.FlatteningPathIterator;
import java.awt.Font;
import javax.swing.JTextPane;

public class SocketFrame extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	
	private JTextPane textPane = new JTextPane();
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					SocketFrame frame = new SocketFrame();
					frame.setVisible(true);					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
	}
	
	

	/**
	 * Create the frame.
	 */
	public SocketFrame() {
		setTitle("聊天");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1000, 700);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(30, 30, 900, 520);
		contentPane.add(scrollPane);
		
		textPane.setEditable(false);
		textPane.setFont(new Font("宋体", Font.PLAIN, 20));
		scrollPane.setViewportView(textPane);
		
		textField = new JTextField();
		textField.setFont(new Font("宋体", Font.PLAIN, 20));
		textField.setBounds(30, 600, 300, 30);
		contentPane.add(textField);
		textField.setColumns(10);
		
		
		JButton btnSend = new JButton("发送");
		btnSend.setFont(new Font("宋体", Font.PLAIN, 20));
		btnSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
						SendRun sendRun=new SendRun();
						Thread sendT=new Thread(sendRun);
						sendT.start();						
						
			}
		
			
		});	
		
		btnSend.setBounds(400, 600, 100, 30);
		contentPane.add(btnSend);
		
		JButton btnStart = new JButton("开始");
		btnStart.setFont(new Font("宋体", Font.PLAIN, 20));
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				ReceiveRun receiveRun=new ReceiveRun();
				Thread receiveT=new Thread(receiveRun);
				receiveT.start();
			}
		});
		btnStart.setBounds(550, 600, 100, 30);
		contentPane.add(btnStart);
				
		
	
		
	}
	
	
	
	
	
	
	//发送数据
	class SendRun implements Runnable{
		
		public void run() {
			DatagramSocket ds;
			
			ArrayList ias=new ArrayList<>();
			ias.add("127.0.0.1");
			
			try {
				ds = new DatagramSocket();
				
				String string=textField.getText();
				SimpleAttributeSet attrset=new SimpleAttributeSet();
				StyleConstants.setForeground(attrset, Color.red);
				Document document=textPane.getDocument();
				document.insertString(document.getLength(), string+"\n", attrset);
				
				byte[] arr=string.getBytes();
				for (String str:ias) {
					DatagramPacket dp=new DatagramPacket(
							arr, arr.length,InetAddress.getByName(str),10087);
					
					ds.send(dp);
				}	
				
				
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	//接受数据
	class ReceiveRun implements Runnable{
		
		DatagramSocket ds;
		
		public void run() {
			try {
				
				ds=new DatagramSocket(10087);
				while (true) {
					byte[] arr=new byte[1024];
					DatagramPacket dp=new DatagramPacket(arr, arr.length);				
					ds.receive(dp);										
					
					String str=new String(dp.getData(),0,dp.getLength());
					
					if ("exit".equals(str)) {
						ds.close();
						break;
					}
					
					String ip=dp.getAddress().getHostAddress();
					
					
					SimpleAttributeSet attrset=new SimpleAttributeSet();
					StyleConstants.setForeground(attrset, Color.blue);
					Document document=textPane.getDocument();
					document.insertString(document.getLength(), ip+" send:"+str+"\n", attrset);
					
					
					
				}
				
				
				
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
			
		}
	}
}

 

你可能感兴趣的:(java)