【学习笔记】网络编程之UDP

网络编程之UDP

 

UDP 发送消息

 

发送端:

  1. 建立一个DatagramSocket,用来传输

  2. 创建一个数据包 DatagramPacket

    • 参数:发送的数据、数据的起始长度,要发给谁(ip地址,端口号)

  3. 用send() 方法 发送数据包

  4. 关闭

package com.network.udp;
​
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 inetAddress = InetAddress.getByName("localhost");
        int port = 9090;
​
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,inetAddress,port);
​
        //发送包
        socket.send(packet);
​
        //关闭
        socket.close();
    }
}

 

接收端:

  1. 开放端口 //DatagramSocket

  2. 接收数据包

    • 需要一个载体,也就是byte数组

  3. 打印发过来的数据

  4. 关闭

package com.network.udp;
​
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().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
​
        //关闭
        socket.close();
    }
}

 

循环发送和接收

 

发送方:

  1. 创建Socket

  2. 从控制台获取数据

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  1. 通过循环发送 包

    • 首先读取从控制台获取的数据

      String data = reader.readLine();
    • 转成 byte 数组类型

    • 发送包

    • 判断是否结束

      if(data.equals("bye")){
          break;   //跳出循环
      }
  2. 关闭

 

完整代码:

package com.network.udp.chat01;
​
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
​
public class UdpSender01 {
    public static void main(String[] args) throws Exception {
        //创建Socket
        DatagramSocket socket = new DatagramSocket(9999);
​
        //从控制台读取数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            String data = reader.readLine();  //读取这一行的数据
            byte[] datas = data.getBytes();
​
            //发送包
            DatagramPacket packet = new DatagramPacket(datas,0,datas.length, new InetSocketAddress("localhost",8888));
            socket.send(packet);
            if (data.equals("bye")){
                break;
            }
        }
        //关闭
        reader.close();
        socket.close();
    }
}

 

 

接收端:

  1. 创建Socket

  2. 循环接收包

    • 准备包的容器 即byte数组

      byte[] buffer = new byte[1024];
      DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
    • 接收包

    • 输出并判断是否要断开

      byte[] data = packet.getData();
      String receiveData = new String(data,0,packet.getLength());
      System.out.println(receiveData);
      if(receiveData.equals("bye")){
          break;
      }
  3. 关闭

 

完整代码:

package com.network.udp.chat01;
​
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
​
public class UdpReceiver01 {
    public static void main(String[] args) throws Exception {
​
        DatagramSocket socket = new DatagramSocket(8888);
​
        while (true){
            //准备接收包裹
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
​
            socket.receive(packet);
            //断开连接
            byte[] data = packet.getData();
​
            String receiveData = new String(data,0, packet.getLength());
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

 

注意:

在把byte 数组 转化成 字符串时,长度要使用 packet.getLength() ,一定不要使用data.length

因为data.length 的长度为1024

之前是可以使用data.length ,但后来spring版本升级后,集成到packet后就不行了

 

UDP 多线程实现聊天

 

线程TalkSend:

package com.network.udp.chap02;
​
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
​
public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private String toIp;
    private int toPort;
    private  int formPort;
​
    public TalkSend(int formPort,String toIp, int toPort) {
        this.toIp = toIp;
        this.toPort = toPort;
        this.formPort = formPort;
​
        try {
            socket = new DatagramSocket(formPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException 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 (IOException e) {
                e.printStackTrace();
            }
        }
        //关闭
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        socket.close();
    }
}

 

线程TalkReceive:

package com.network.udp.chap02;
​
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[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
​
                socket.receive(packet);
                //断开连接
                byte[] data = packet.getData();
​
                String receiveData = new String(data,0, packet.getLength());
                System.out.println(msgFrom+":"+receiveData);
                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

 

TalkStudent类:

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

 

TalkTeacher类:

package com.network.udp.chap02;
​
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(9988,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }
}

 

posted @ 2022-07-30 16:16  GrowthRoad  阅读(36)  评论(0编辑  收藏  举报