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

2023-12-06 15:28

本文主要是介绍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的聊天

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

这篇关于Java利用UDP实现简单的双人聊天的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/462324

相关文章

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

一份LLM资源清单围观技术大佬的日常;手把手教你在美国搭建「百万卡」AI数据中心;为啥大模型做不好简单的数学计算? | ShowMeAI日报

👀日报&周刊合集 | 🎡ShowMeAI官网 | 🧡 点赞关注评论拜托啦! 1. 为啥大模型做不好简单的数学计算?从大模型高考数学成绩不及格说起 司南评测体系 OpenCompass 选取 7 个大模型 (6 个开源模型+ GPT-4o),组织参与了 2024 年高考「新课标I卷」的语文、数学、英语考试,然后由经验丰富的判卷老师评判得分。 结果如上图所

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001