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

news/2024/5/18 14:41:19 标签: 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的聊天


http://www.niftyadmin.cn/n/5242657.html

相关文章

第十章 tornado

Python基础、函数、模块、面向对象、网络和并发编程、数据库和缓存、 前端、django、Flask、tornado、api、git、爬虫、算法和数据结构、Linux、设计题、客观题、其他 第十章 tornado 1. tornado中的gen.coroutine的作用&#xff1f; 在Tornado框架中&#xff0c;gen.corouti…

在内核中阻止进程创建的正确方法

最近遇到一个BUG&#xff0c;通过Word在打开hyperlink时&#xff0c;在进程通知回调中结束了Chrome浏览器进程&#xff0c;目标进程虽然被杀了&#xff0c;但是Word还会再尝试用另一种方法再打开浏览器&#xff0c;这种情况只出现在Win7上&#xff0c;百思不得其解。。。最终定…

Android的前台服务

概述 前台服务是用户主动意识到的一种服务&#xff0c;因此在内存不足时&#xff0c;系统也不会考虑将其终止。前台服务必须为状态栏提供通知&#xff0c;将其放在运行中的标题下方。这意味着除非将服务停止或从前台移除&#xff0c;否则不能清除该通知。 在 Android 8.0&…

springboot 整合 Spring Security+JWT 实现token 认证和校验

1.大概是这个样子 JWT 是什么&#xff1f; Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准&#xff08;(RFC 7519).该token被设计为紧凑且安全的&#xff0c;特别适用于分布式站点的单点登录&#xff08;SSO&#xff09;场景。JWT的声明…

前端小记--3.接上篇,级联组件el-cascader回显问题

在使用el-cascader这个级联组件时&#xff0c;组件的值是数组形式&#xff0c;且选中节点时&#xff0c;所返回的值中是包含选中节点的所有父节点的。 比如&#xff0c;我们选中的是“值班点1号-东门”&#xff0c;但组件实际的值是[‘值班点1号’,‘值班点1号-东门’]&#x…

Qt绘制直线箭头

一.使用QPainter绘制 满足条件: 任意角度直线都可绘制箭头所有箭头同样大小 void MainWindow::paintEvent(QPaintEvent*) {QPainter painter(this); // 创建QPainter对象&#xff0c;并指定绘制目标为当前的widgetQLineF line(50,20,500,500);double distanceFromEnd1 20;qre…

JPA构建多条件查询

方式一 new Specification匿名内部类&#xff0c;通过实现该匿名内部类的toPredicate方法构建查询sql Specification<T> specification new Specification<T>() {Overridepublic Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, Cri…

【JavaEE进阶】 Spring 的创建和使⽤

文章目录 &#x1f334;前言&#x1f38b;创建 Spring 项⽬&#x1f6a9;创建⼀个 Maven 项⽬&#x1f6a9;添加 Spring 框架⽀持&#x1f6a9;添加启动类 &#x1f333;存储 Bean 对象&#x1f6a9;创建Bean&#x1f6a9;将 Bean 注册到容器 &#x1f332;获取并使⽤ Bean 对象…