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

news/2024/10/22 14:26:25/

一、创建新项目
首先创建一个新的项目,并命名。

二、实现代码
 
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的聊天


http://www.ppmy.cn/news/1259742.html

相关文章

【LeetCode 0125】【双指针】有效回文

题目 https://leetcode.com/problems/valid-palindrome/ 题解 双指针&#xff1a;左指针右移过程时跳过非法字符&#xff0c;右指针左移时跳过非法字符。 如果左指针大于等于右指针&#xff0c;表示有效回文&#xff1b;如果两指针所对应的字符如果不等&#xff0c;则不是有…

利用python编写后端程序 通用代码详解 项目实现

前言 最近自己正好有时间&#xff0c;想要自己搭建微信小程序&#xff0c;也正好记录一下自己的搭建过程和内容。 搭建准备工作 这里我使用的时pycharm编辑器。在后端开发中&#xff0c;我们需要三个库&#xff1a; import pymysql from flask import request, Fl…

batch_size太大和太小的优缺点分别是什么?

在深度学习的实验当中&#xff0c;我们通常回去设置batch_size&#xff0c;那batch_size开的太大和太小分别会为我们带来什么样的优缺点呢&#xff1f; 批处理大小过大&#xff1a; 优点&#xff1a; 训练速度较快&#xff1a;大批次可以充分利用硬件加速器&#xff08;如GP…

云上守沪 | 云轴科技ZStack成功实践精选(上海)

为打造国际数字之都&#xff0c;上海发布数字经济发展“十四五”规划&#xff0c;围绕数字新产业、数据新要素、数字新基建、智能新终端等重点领域&#xff0c;加强数据、技术、企业、空间载体等关键要素协同联动&#xff0c;加快进行数字经济发展布局&#xff1b;加快基础软件…

c# OpenCV安装(一)

一 通过NuGet 安装四个拓展包 OpenCvSharp4、OpenCvSharp4.Extensions、OpenCvSharp4.runtime.win、OpenCvSharp4.WpfExtensions C#使用OpenCV的一些代码 需要加头文件 using OpenCvSharp; //为了使用opencv using Point OpenCvSharp.Point; //为了确定我们使用的poin…

Python中字符串拼接及其应用场景

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com 字符串拼接是Python中常见而重要的操作&#xff0c;它涉及到将多个字符串连接成一个字符串。本文将深入探讨Python中字符串拼接的不同方式、性能比较、以及在实际应用中的场景和最佳实践。 常见的字符串拼接方法…

智能优化算法应用:基于白冠鸡算法无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于白冠鸡算法无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于白冠鸡算法无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.白冠鸡算法4.实验参数设定5.算法结果6.参考文献7.…

Qt Creator 11.0.3同时使用Qt6.5和Qt5.14.2

Qt Creator 11.0.3同时使用Qt6.5和Qt5.14.2 概要方法1.打开Qt Creator中的Kit&#xff0c;这里我直接附上几张截图&#xff0c;不同的版本打开位置可能有所不同&#xff0c;总之最终目的是要打开构建套件&#xff08;Kit&#xff09;2.可以看到构建套件里面有包含了“构建套件K…