当前位置: 首页 > news >正文

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();}}

结果:

相关文章:

  • C++ 多态性(Polymorphism)和 虚函数(Virtual Functions)
  • Kubernetes里的DNS;API资源对象ingress;Kubernetes调度;节点选择器NodeSelector;节点亲和性NodeAffinity
  • 五:爬虫-数据解析之xpath解析
  • 【C++】简单工厂模式
  • C++STL的string(超详解)
  • 大量 SVG 图标在 React 中的极速集成与应用
  • MySQL概述-安装与启动
  • P1317 低洼地题解
  • 【Flutter】vs2022上开发flutter
  • 免费的SEO外链发布工具,提升排名的利器
  • 63. 不同路径 II
  • 二叉搜索树中第K小的元素[中等]
  • unittest与pytest的区别
  • 【已解决】解决UbuntuKali无法进行SSH远程连接
  • 理解基于 Hadoop 生态的大数据技术架构
  • ECS应用管理最佳实践
  • fetch 从初识到应用
  • maven工程打包jar以及java jar命令的classpath使用
  • npx命令介绍
  • Quartz实现数据同步 | 从0开始构建SpringCloud微服务(3)
  • Vue小说阅读器(仿追书神器)
  • XML已死 ?
  • 经典排序算法及其 Java 实现
  • 老板让我十分钟上手nx-admin
  • 移动端 h5开发相关内容总结(三)
  • ​IAR全面支持国科环宇AS32X系列RISC-V车规MCU
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • #define、const、typedef的差别
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (70min)字节暑假实习二面(已挂)
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (读书笔记)Javascript高级程序设计---ECMAScript基础
  • (二)Pytorch快速搭建神经网络模型实现气温预测回归(代码+详细注解)
  • (附源码)springboot 房产中介系统 毕业设计 312341
  • (附源码)springboot教学评价 毕业设计 641310
  • (回溯) LeetCode 40. 组合总和II
  • (十三)Flink SQL
  • (四)事件系统
  • .cfg\.dat\.mak(持续补充)
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET Core工程编译事件$(TargetDir)变量为空引发的思考
  • .net framework 4.8 开发windows系统服务
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)
  • .Net开发笔记(二十)创建一个需要授权的第三方组件
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?
  • /proc/stat文件详解(翻译)
  • []AT 指令 收发短信和GPRS上网 SIM508/548
  • [000-01-011].第2节:持久层方案的对比
  • [20150629]简单的加密连接.txt
  • [20171113]修改表结构删除列相关问题4.txt
  • [Algorithm][综合训练][体育课测验(二)][合唱队形][宵暗的妖怪]详细讲解
  • [Android Studio 权威教程]断点调试和高级调试
  • [Android]使用Android打包Unity工程
  • [boost]使用boost::function和boost::bind产生的down机一例