UDP多人群聊

一.创建类

二.类

1.Liao类

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.IOException;
import java.lang.String;public class Liao 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(Liao.this,"请输入IP地址和端口号");return;}if(datagramSoket==null||datagramSoket.isClosed()){JOptionPane.showMessageDialog(Liao.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(Liao.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) {Liao a=new Liao();a.setUpUI();a.initSocket();a.setListener();}}

三.结果

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/203041.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

QT使用http通信的同步和异步

在Qt与Http通信的时候&#xff0c;会根据不同的情况使用同步或者异步的方式进行数据请求。 同步&#xff0c;即发送Http请求之后&#xff0c;会一直等待服务器返回的数据&#xff0c;接收到数据之前&#xff0c;程序一直阻塞。 异步&#xff0c;即发送Http请求之后&#xff0…

【musl-pwn】msul-pwn 刷题记录 -- musl libc 1.2.2

前言 本文不分析 musl libc 相关源码&#xff0c;仅仅为刷题记录&#xff0c;请读者自行学习相关知识&#xff08;看看源码就行了&#xff0c;代码量也不大&#xff09; starCTF2022_babynote 保护&#xff1a;保护全开 程序与漏洞分析&#xff1a; 程序实现了一个菜单堆&…

自适应局部降噪滤波器的python实现-------冈萨雷斯数字图像处理

自适应局部降噪滤波器 自适应局部降噪滤波器是一种信号处理技术&#xff0c;用于降低图像或信号中的噪声水平&#xff0c;同时保留图像或信号的细节。其原理基于局部区域内信号的统计特性和噪声的特征&#xff0c;通过动态调整滤波器的参数来适应不同区域的信号和噪声属性。 自…

Mac系统升级node.js版本和npm版本

升级node.js版本 第一步&#xff1a;查询当前node.js版本 node -v 第二步&#xff1a;清除node.js的缓存 sudo npm cache clean -f 第三步&#xff1a;验证缓存是否清空 npm cache verify 第四步&#xff1a;安装n工具&#xff0c;n工具是专门用于管理node.js版本的工具…

Day52力扣打卡

打卡记录 Collapsing Strings&#xff08;Trie树&#xff09; 链接 #include <iostream> #include <algorithm> using namespace std; const int N 2e6 10; int son[N][26], idx, cnt1[N], cnt2[N]; int main() {auto insert [&](string& str, int* c…

【Qt】在表格QTableWidget或者QTableView中,当主键Id存在时更新数据,不存在时添加数据解决方案

问题 有时在开发中&#xff0c;表格需要显示数据&#xff0c;每一行呢&#xff0c;需要记录对应的id。 当更新表格数据时&#xff0c;会根据id进行更新&#xff0c;id存在就更新行数据&#xff0c;不存在就添加一行新数据。 解决方案 如何知道id存在还是不存在呢&#xff1f…

记一次CDH集群迁移产生的问题——HIVE

背景 生产环境CDH集群迁移到新的环境&#xff0c;迁移之后使用Hive Client方执行任务一直失败。 问题1&#xff1a;metadata.SessionHiveMetaStoreClient 产生报错&#xff1a; FAILED: SemanticException org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.Ru…

AOP操作日志记录

AOP操作日志记录 1.创建注解 Retention(RetentionPolicy.RUNTIME) Target(ElementType.METHOD) public interface PassportLog {String operatePage();String operateType();ClassTypEnum classType();}2.创建切面 对于字典&#xff0c;可以通过注解属性去转换&#xff0c;枚举…

车联网架构设计(二)_消息缓存

在上一篇博客车联网架构设计(一)_消息平台的搭建-CSDN博客中&#xff0c;我介绍了车联网平台需要实现的一些功能&#xff0c;并介绍了如何用EMQXHAPROXY来搭建一个MQTT消息平台。车联网平台的应用需要消费车辆发布的消息&#xff0c;同时也会下发消息给车辆&#xff0c;以实现车…

SpringBoot 属性配置解析

属性配置介绍 spring官方提供的17中属性配置的方式 Devtools全局配置测试环境TestPropertySource注解测试环境properties属性命令行参数SPRING_APPLICATION_JSON属性ServletConfig初始化参数ServletContext初始化参数JNDI属性JAVA系统属性操作系统环境变量RandomValueProperty…

解释区块链技术的应用场景和优势。

区块链技术的应用场景&#xff1a; 金融行业&#xff1a;区块链可用于加强支付、结算、借贷和保险等金融业务的安全性和效率。 物流行业&#xff1a;区块链可用于追踪物流信息&#xff0c;保证货物的安全、可靠和透明。 版权保护&#xff1a;区块链可用于储存数字资产和版权信…

Nacos和Eureka冲突问题原因分析

目录 一、问题现象二、解决办法三、原因分析 一、问题现象 Description:Field autoServiceRegistration in org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration required a single bean, but 2 were found:- eurekaAutoServiceRegis…

单例模式【C#】

只能生一个儿子。 文件操作只能一个单例去操作。 1static&#xff1a; static的特点是&#xff0c;不需要new就能使用。即使派生了&#xff0c;也是使用静态的对象。 public class SingleObject {//创建 SingleObject 的一个对象private static SingleObject instance new…

基于OpenCV+CNN+IOT+微信小程序智能果实采摘指导系统——深度学习算法应用(含pytho、JS工程源码)+数据集+模型(二)

目录 前言总体设计系统整体结构图系统流程图 运行环境Python环境TensorFlow 环境Jupyter Notebook环境Pycharm 环境微信开发者工具OneNET云平台 相关其它博客工程源代码下载其它资料下载 前言 本项目基于Keras框架&#xff0c;引入CNN进行模型训练&#xff0c;采用Dropout梯度…

spark log4j日志配置

1.spark启动参数 先把log4j配置文件放到hdfs&#xff1a;hdfs://R2/projects/log4j-debug.properties --conf spark.yarn.dist.fileshdfs://R2/projects/log4j-debug.properties#log4j-first.properties \ --conf "spark.driver.extraJavaOptions-Dlog4j.configurationf…

【前端设计模式】之单例模式

在前端开发中&#xff0c;单例模式是一种常见的设计模式&#xff0c;用于确保一个类只有一个实例&#xff0c;并提供全局访问点。在实现单例模式时&#xff0c;有一些最佳实践和高级技巧可以帮助我们编写更优雅和可维护的代码。 1. 使用闭包 使用闭包是实现单例模式的一种常见…

uni-app 设置tabBar的setTabBarBadge购物车/消息等角标

目录 一、效果二、代码实现二、全部代码1.index.vue2.cart.vue 三、真实案例参考最后 一、效果 二、代码实现 只要使用uni.setTabBarBadge和uni.removeTabBarBadge来进行对红点的设置和移除。 主要代码&#xff1a; //设置红点 uni.setTabBarBadge({index: 1, // 底部菜单栏…

大数据可视化项目——基于Python豆瓣电影数据可视化分析系统的设计与实现

大数据可视化项目——基于Python豆瓣电影数据可视化分析系统的设计与实现 本项目旨在通过对豆瓣电影数据进行综合分析与可视化展示&#xff0c;构建一个基于Python的大数据可视化系统。通过数据爬取收集、清洗、分析豆瓣电影数据&#xff0c;我们提供了一个全面的电影信息平台…

Python自动化——driver.execute_script的用法

用法引入 当您使用Selenium时&#xff0c;您可以指定chrome驱动程序的路径。以下是一个完整的示例&#xff0c;包括指定Chrome驱动程序的路径&#xff1a; from selenium import webdriver# 指定Chrome驱动程序的路径 chrome_driver_path C:/path/to/your/chromedriver.exe …

2-Django、Flask和Tornado三大主流框架对比

在Python的web开发框架中&#xff0c;目前使用量最高的几个是Django、Flask和Tornado&#xff0c; 经常会有人拿这几个对比&#xff0c;相信大家的初步印象应该是 Django大而全、Flask小而精、Tornado性能高。 了解常用框架 Django 主要特点是大而全,集成了很多组件,例如: Mo…