UDP实现群聊

news/2024/5/18 16:36:47 标签: 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=8899;
	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("聊天");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(400,400);
		setResizable(false);//窗口大小不可改变
		setLocationRelativeTo(null);//设置窗口相对于指定组件的位置
		stateLB=new JLabel("weijianting");
		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();
		}
		
}

结果:

 

 


http://www.niftyadmin.cn/n/5249474.html

相关文章

基于Java旅游信息管理系统

基于Java旅游信息管理系统 功能需求 1、旅游目的地管理&#xff1a;系统需要能够记录和管理各个旅游目的地的详细信息&#xff0c;包括景点介绍、交通方式、住宿推荐等。管理员可以添加、编辑和删除目的地信息。 2、旅游线路规划&#xff1a;系统需要提供旅游线路规划功能&a…

Python与ArcGIS系列(十六)重复节点检测

目录 0 简述1 实例需求2 arcpy开发脚本0 简述 在处理gis线图层和面图层数据时,有时候会遇到这种情况:数据存在重复节点或伪重复节点(两个节点距离极小),往往我们需要对这种数据进行检测标注或进行修改。本篇将介绍如何利用arcpy及arcgis的工具箱实现这个功能。 1 实例需求…

QT作业2

使用手动连接&#xff0c;将登录框中的取消按钮使用qt4版本的连接到自定义的槽函数中&#xff0c;在自定义的槽函数中调用关闭函数 将登录按钮使用qt5版本的连接到自定义的槽函数中&#xff0c;在槽函数中判断ui界面上输入的账号是否为"admin"&#xff0c;密码是否为…

C++如何通过调用ffmpeg接口对H265文件进行编码和解码

要对H265文件进行编码和解码&#xff0c;需要使用FFmpeg库提供的相关API。以下是一个简单的C程序&#xff0c;演示如何使用FFmpeg进行H265文件的编码和解码&#xff1a; 编码&#xff1a; #include <cstdlib> #include <cstdio> #include <cstring> #inclu…

Flask template中使用iframe

Flaks template中使用iframe嵌套新的网页&#xff08;new_page.html&#xff09;的网页到历史网页&#xff08;old_page.html&#xff09;中&#xff08;减少新网页的入口&#xff09; 1,增加iframe tag 在old_page.html中适当位置增加iframe入口标签&#xff1a; <ifram…

C_15练习题

一、单项选择题(本大题共20小题,每小题2分,共40分。在每小题给出的四个备选须中选出一个正确的答案,并将所选项前的字母填写在答题纸的相应位置上。) C程序是由&#xff08;&#xff09;构成的。 A.常量 B.变量 C.运算符 D. 函数 下列合法的标识符是&#xff08;&#xff09; …

YOLOv4 学习笔记

文章目录 前言一、YOLOv4贡献和改进二、YOLOv4核心概念三、YOLOv4网络架构四、YOLOv4数据增强五、YOLOv4的损失函数总结 前言 在近年来的目标检测领域&#xff0c;YOLOv4的出现标志着一个重要的技术突破。YOLOv4不仅继承了YOLO系列快速、高效的特点&#xff0c;还引入了一系列…

使用AWS Glue与AWS Kinesis构建的流式ETL作业(一)——数据实时采集

大纲 1 数据采集准备工作1.1 研究的背景1.2 使用Glue构建流式ETL的原因1.3 无服务器流式ETL架构1.4 架构1.5 AWS Kinesis Data Stream创建1.6 AWS CloudWatch数据筛选1.6.1 AWS IAM角色权限1.6.1.1 可信实体1.6.1.2 策略 1.7 AWS Kinesis中的数据验证1.7.1 验证代码1.7.2 结果 …