当前位置: 首页 > 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();}}

结果:

 

 

http://www.lryc.cn/news/256584.html

相关文章:

  • 服务器部署网易开源TTS | EmotiVoice部署教程
  • 贪心算法和动态规划
  • jsp 设备预约管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • Python:核心知识点整理大全10-笔记
  • Hive数据库系列--Hive数据类型/Hive字段类型/Hive类型转换
  • 在Spring Cloud中使用组件Ribbon和Feign,并分别创建子模块注册到Eureka中去
  • (JAVA)-缓冲流
  • Autosar UDS-CAN诊断开发02-1(CAN诊断帧格式类型详解、CANFD诊断帧格式类型详解、15765-2(CANTP层)的意义)
  • swing快速入门(三)
  • Swagger PHP Thinkphp 接口文档
  • 12.9每日一题(备战蓝桥杯循环结构)
  • 与时代共进退
  • Python 云服务器应用,Https,定时重启
  • pytorch 笔记:dist 和 cdist
  • Java的List中的各种浅拷贝和深拷贝问题
  • 20231207_最新已测_Centos7.4安装nginx1.24.0_安装详细步骤---Linux工作笔记066
  • 前端知识笔记(二十六)———React如何像Vue一样将css和js写在同一文件
  • Photoshop Circular Text
  • 深入解析Spring Boot中的注解@PathVariable、@RequestParam、@RequestBody的正确使用
  • Qt Location中加载地图对象
  • 4-Docker命令之docker ps
  • 你在地铁上修过bug吗?
  • CPU、MCU、MPU、DSP、FPGA各是什么?有什么区别?
  • SpringBoot之logback 在Linux系统上启动的时候,设置日志按日期分割并设置指定时间自动清除日志
  • OpenHarmony北向-让更广泛的应用开发者更容易参与
  • 数据结构之归并排序及排序总结
  • 仿windows12网盘,私有云盘部署教程,支持多种网盘
  • 深度学习 时间序列回归学习笔记
  • 【postgresql】ERROR: INSERT has more expressions than target columns
  • Android Kotlin语言下的文件存储