(网络编程)UDP实现聊天

文章目录

  • UDP实现聊天
    • 单线程发送接收数据
      • 发送方代码
      • 接收方代码
    • 多线程实现双方互相发送数据
      • 首先编写发送和接收的Runnable实现类
      • 双方线程创建启动

UDP实现聊天

我们知道UDP无需建立连接就可发送信息,就像QQ一样,无论对方是否在线,你都可以发送消息。下面用UDP来实现聊天功能。

单线程发送接收数据

发送方发送数据
(网络编程)UDP实现聊天_第1张图片
接收方接收数据
(网络编程)UDP实现聊天_第2张图片

发送方代码

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class Demo01Sender {
    public static void main(String[] args) throws Exception {
        //1.建立一个socket,参数是自己的端口号
        DatagramSocket socket = new DatagramSocket(8888);
        //准备数据,控制台读取输入
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {

            String data = reader.readLine();
            byte[] datas = data.getBytes();
            //2.创建数据包
            //参数:数据,数据开始点,数据长度,发送的地址
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
            //3.发送数据包
            socket.send(packet);
            if (data.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

接收方代码

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Demo01Receiver {
    public static void main(String[] args) throws Exception {
        //1.创建socket
        DatagramSocket socket = new DatagramSocket(6666);
        while (true) {
            //2.准备接收包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            //3.阻塞式接受包裹
            socket.receive(packet);

            //显示接受数据
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }

        socket.close();
    }
    }


多线程实现双方互相发送数据

上述代码只能实现单方发送与接收,而要实现双方互相发送数据和接收数据则要用到多线程。
佐伊
(网络编程)UDP实现聊天_第3张图片
伊泽瑞尔
(网络编程)UDP实现聊天_第4张图片

首先编写发送和接收的Runnable实现类

发送

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
    }

    @Override
    public void run() {
        //1.建立一个socket,参数是自己的端口号
        try {
            socket = new DatagramSocket(fromPort);
            //准备数据,控制台读取输入
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }

        while (true) {
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();
                //2.创建数据包
                //参数:数据,数据开始点,数据长度,发送的地址
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(toIP, toPort));
                //3.发送数据包
                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }

}

接收

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

public class TalkReceive implements Runnable{
    DatagramSocket socket=null;
    private int port;
    private String msgFrom;
    public TalkReceive(int port ,String msgFrom) {
        this.port = port;
        this.msgFrom = msgFrom;
    }

    @Override
    public void run() {
        //1.创建socket
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (true) {

            try {
                //2.准备接收包裹
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                //3.阻塞式接受包裹
                socket.receive(packet);
                //显示接受数据
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom+":"+receiveData);
                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

        socket.close();
    }
}

双方线程创建启动

佐伊

public class TalkZoe {
    public static void main(String[] args) {
        new Thread(new TalkSend(2222,"localhost",8888)).start();
        new Thread(new TalkReceive(6666,"伊泽瑞尔")).start();
    }
}

伊泽瑞尔

public class TalkEz {
    public static void main(String[] args) {
        new Thread(new TalkSend(3333,"localhost",6666)).start();
        new Thread(new TalkReceive(8888,"佐伊")).start();
    }
}

你可能感兴趣的:(网络编程)