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

三.结果

相关推荐

  1. <span style='color:red;'>UDP</span>群<span style='color:red;'>聊</span>

    UDP

    2023-12-12 20:52:03      27 阅读
  2. <span style='color:red;'>UDP</span>群<span style='color:red;'>聊</span>

    UDP

    2023-12-12 20:52:03      38 阅读
  3. <span style='color:red;'>UDP</span>群<span style='color:red;'>聊</span>

    UDP

    2023-12-12 20:52:03      36 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-12 20:52:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-12 20:52:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-12 20:52:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-12 20:52:03       20 阅读

热门阅读

  1. 在本地机器上部署最小化k8s环境

    2023-12-12 20:52:03       38 阅读
  2. 使用python脚本一个简单的搭建ansible集群

    2023-12-12 20:52:03       34 阅读
  3. 单例模式——懒汉模式的双重检测锁问题

    2023-12-12 20:52:03       34 阅读
  4. 设计模式之:与设计模式相处

    2023-12-12 20:52:03       35 阅读
  5. 分布式学习一

    2023-12-12 20:52:03       30 阅读
  6. 装饰器的典型行为

    2023-12-12 20:52:03       32 阅读
  7. 在Vue中 .sync作用

    2023-12-12 20:52:03       46 阅读
  8. 升级jdk1.8u391后,加解密部分报错解决

    2023-12-12 20:52:03       51 阅读
  9. 选择法排序

    2023-12-12 20:52:03       38 阅读
  10. 【Flink on k8s】 -- flink kubernetes operator 1.7.0 发布

    2023-12-12 20:52:03       40 阅读
  11. C语言——assert函数

    2023-12-12 20:52:03       40 阅读