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

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解