Java中通过UDP来实现简易聊天室功能

在Java中通过UDP来实现简易的聊天室功能

方法一:使用线程


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class _UDP简易聊天室by线程 {
    public static void main(String[] args) {
        new Thread(new Sender()).start();
        new Thread(new Receiver()).start();
    }
}

class Sender implements Runnable {

    @Override
    public void run() {
        //
        try {
            DatagramSocket ds = new DatagramSocket();
            Scanner sc = new Scanner(System.in);
            while (true) {
                byte[] message = sc.nextLine().getBytes();
                DatagramPacket dp = new DatagramPacket(message,
                        message.length,
                        new InetSocketAddress("255.255.255.255", 8091));

                ds.send(dp);


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class Receiver implements Runnable {

    @Override
    public void run() {
        try {
            DatagramSocket ds = new DatagramSocket(8091);
            DatagramPacket dp = new DatagramPacket(new byte[1024], 1024);

            while (true) {
                ds.receive(dp);
                System.out.println(dp.getAddress());
                System.out.println(new String(dp.getData(), 0, dp.getLength()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

方法二:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class _UDP简易聊天室接收端 {
    public static void main(String[] args) throws IOException {
        while (true) {
            DatagramSocket ds = new DatagramSocket(8091);

            DatagramPacket dp = new DatagramPacket(new byte[100], 100);

            ds.receive(dp);
            ds.close();


            System.out.println(dp.getAddress());

            System.out.println(new String(dp.getData(), 0, dp.getLength()));
        }
    }
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

public class _UDP简易聊天室发送端 {
    public static void main(String[] args) throws IOException {
        boolean flag = true;
        while (flag == true) {
            Scanner sc = new Scanner(System.in);
            String message = sc.nextLine();
            DatagramSocket ds = new DatagramSocket();
            DatagramPacket dp = new DatagramPacket(message.getBytes(),
                    message.getBytes().length,
                    new InetSocketAddress("127.0.0.1", 8091));
            flag = false;
            //发送数据包
            ds.send(dp);

            //关流
            ds.close();
            flag = true;
        }
    }
}

上一篇:QCustomplot(二) 源码解读


下一篇:JavaSE-21.2.2【案例-UDP通信程序(“多人聊天室”)】