Java实现UDP(聊天)

Java实现UDP

不需要连接,需要知道地址和接口。

  • 发送消息
package com.davis.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //建立一个socket
        DatagramSocket socket=new DatagramSocket();


        String msg="你好,服务器";

        //发送信息
        InetAddress localhost=InetAddress.getByName("localhost");
        int port=9090;

        //建包
        DatagramPacket packet=new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);

        //发送
        socket.send(packet);

        socket.close();

    }

}
  • 接收消息

    package com.davis.lesson03;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    public class UdpServerDemo01  {
        public static void main(String[] args) throws Exception{
            //开放端口
            DatagramSocket socket=new DatagramSocket(9090);
    
            //接收数据包
            byte[]buffer=new byte[1024];
            DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
            socket.receive(packet);
    
            System.out.println(packet.getAddress().getHostName());
            System.out.println(new String(packet.getData(),0,packet.getLength()));
    
            socket.close();
    
    
        }
    
    
    }
    
  • 使用线程实现聊天

    send

    package com.davis.chart;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetSocketAddress;
    
    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;
    
            try{
                socket=new DatagramSocket(fromPort);
                reader=new BufferedReader(new InputStreamReader(System.in));
            }catch (Exception e){
                e.printStackTrace();
            }
    
    
        }
    
        @Override
        public void run() {
            while(true) {
                try{
                    String data=reader.readLine();
                    byte[] datas = data.getBytes();
                    DatagramPacket packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIp,this.toPort));
                    socket.send(packet);
                    if(data.equals("bye")){
                        break;
                    }
    
                }catch (Exception e){
                    e.printStackTrace();
                }
    
    
            }
    
    
            socket.close();
    
        }
    }
    

    receive

    package com.davis.chart;
    
    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;
            try {
                socket=new DatagramSocket(port);
            } catch (SocketException e) {
                e.printStackTrace();
            }
    
        }
    
        @Override
        public void run() {
    
            while(true){
                try {
                    //准备接受包裹
                    byte[] container = new byte[1024];
                    DatagramPacket packet=new DatagramPacket(container,0,container.length);
                    socket.receive(packet);
    
                    //断开连接 bye
                    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();
    
    
        }
        }
    
  • 学生端

    package com.davis.chart;
    
    public class TalkStudent {
        public static void main(String[] args) {
            //开启两个线程
            new Thread(new TalkSend(7777,"localhost",9999)).start();
            new Thread(new TalkReceive(8888,"老师")).start();
    
        }
    }
    
  • 教师端

    package com.davis.chart;
    
    public class TalkTeacher {
        public static void main(String[] args) {
            new Thread(new TalkSend(5555,"localhost",8888)).start();
            new Thread(new TalkReceive(9999,"学生")).start();
    
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leon_davis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值