Java利用UDP实现简单的双人聊天

一、创建新项目

首先创建一个新的项目,并命名。

二、实现代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.IOException;
import java.lang.String;
 
public class liaotian extends JFrame{
	private static final int DEFAULT_PORT=1;//端口名
	private JLabel stateLB;
	private JTextArea centerTextArea;
	private JPanel southPanel;
	private JTextArea inputTextArea;
	private JPanel bottomPanel;
	private JTextField ipTextField;
	private JTextField remotePortTF;
	private JButton sendBT;
	private JButton clearBT;
	private DatagramSocket datagramSoket;
	private void setUpUI(){
		setTitle("GUI");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,400);
		setResizable(false);//窗口大小不可改变
		setLocationRelativeTo(null);//设置窗口相对于指定组件的位置
		stateLB=new JLabel("聊天室");
		stateLB.setHorizontalAlignment(JLabel.RIGHT);
		centerTextArea=new JTextArea();
		centerTextArea.setEditable(false);
		centerTextArea.setBackground(new Color(211,211,211));
		southPanel=new JPanel(new BorderLayout());
		inputTextArea=new JTextArea(5,20);
		bottomPanel=new JPanel(new FlowLayout(FlowLayout.CENTER,5,5));
		ipTextField=new JTextField("127.0.0.1",8);
		remotePortTF=new JTextField(String.valueOf(DEFAULT_PORT),3);
		sendBT=new JButton("发送");
		clearBT=new JButton("清屏");
		bottomPanel.add(ipTextField);
		bottomPanel.add(remotePortTF);
		bottomPanel.add(sendBT);
		bottomPanel.add(clearBT);
		southPanel.add(new JScrollPane(inputTextArea),BorderLayout.CENTER);
		southPanel.add(bottomPanel,BorderLayout.SOUTH);
		add(stateLB,BorderLayout.NORTH);
		add(new JScrollPane(centerTextArea),BorderLayout.CENTER);
		add(southPanel,BorderLayout.SOUTH);
		setVisible(true);
	}
private void setListener(){
	sendBT.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			final String ipAddress=ipTextField.getText();
			final String remotePort=remotePortTF.getText();
			if(ipAddress==null||ipAddress.trim().equals("")||remotePort==null||remotePort.trim().equals("")){
				JOptionPane.showMessageDialog(liaotian.this,"请输入IP地址和端口号");
				return;
			}
			if(datagramSoket==null||datagramSoket.isClosed()){
				JOptionPane.showMessageDialog(liaotian.this,"监听未成功");
				return;
			}
			String sendContent=inputTextArea.getText();
			byte[] buf=sendContent.getBytes();
			try{
				centerTextArea.append("我对"+ipAddress+":"+remotePort+"说:\n"+inputTextArea.getText()+"\n\n");
				centerTextArea.setCaretPosition(centerTextArea.getText().length());
				datagramSoket.send(new DatagramPacket(buf,buf.length,InetAddress.getByName(ipAddress),Integer.parseInt(remotePort)));
				inputTextArea.setText("");
			}catch(IOException e1){
				JOptionPane.showMessageDialog(liaotian.this, "出错了,发送不成功");
				e1.printStackTrace();
			}
		};
	});
	clearBT.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){
			centerTextArea.setText("");
		}
	});
}
private void initSocket(){
	int port=DEFAULT_PORT;
	while(true){
		try{
			if(datagramSoket!=null&&!datagramSoket.isConnected()){
				datagramSoket.close();
			}
			try{
				port=Integer.parseInt(JOptionPane.showInputDialog(this,"请输入端口号","端口号",JOptionPane.QUESTION_MESSAGE));
				if(port<1||port>65535){
					throw new RuntimeException("端口号超出范围");
				}
			}catch(Exception e){
				JOptionPane.showMessageDialog(null,"你输入的端口不正确,请输入1~65535之间的数");
				continue;
			}
			datagramSoket=new DatagramSocket(port);
			startListen();
			stateLB.setText("已在"+port+"端口监听");
			break;
		}catch(SocketException e){
			JOptionPane.showMessageDialog(this, "端口号被占用,请重新设置端口");
			stateLB.setText("当前未启动监听");
		}
	}
}
private void startListen(){
	new Thread(){
		private DatagramPacket p;
		public void run(){
			byte[] buf=new byte[1024];
			p=new DatagramPacket(buf,buf.length);
			while(!datagramSoket.isConnected()){
				try{
					datagramSoket.receive(p);
					centerTextArea.append(p.getAddress().getHostAddress()+":"+((InetSocketAddress)p.getSocketAddress()).getPort()+"对我说:\n"+new String(p.getData(),0,p.getLength())+"\n\n");
					centerTextArea.setCaretPosition(centerTextArea.getText().length());
				}catch(IOException e){
					e.printStackTrace();
				}
			}
		}
	}.start();
}
		public static void main(String[] args) {
			liaotian a=new liaotian();
            a.setUpUI();
			a.initSocket();
			a.setListener();
		}
		
}

三、运行结果

用户1和用户2的聊天

注意:只能一对一聊天,否则会弹出如下图所示:

相关推荐
Dola_Pan24 分钟前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book27 分钟前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
AI原吾1 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
机器视觉知识推荐、就业指导1 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
毕设木哥1 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
珞瑜·1 小时前
Matlab R2024B软件安装教程
开发语言·matlab
weixin_455446171 小时前
Python学习的主要知识框架
开发语言·python·学习
孤寂大仙v1 小时前
【C++】STL----list常见用法
开发语言·c++·list
蜗牛^^O^1 小时前
Docker和K8S
java·docker·kubernetes
她似晚风般温柔7892 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app