网络通信协议 UDP与TCP协议

public static void main(String[] args) throws UnknownHostException {
        // 获取本地inet对象
        InetAddress inet= InetAddress.getLocalHost();
        System.out.println(inet);
        //根据主机名/ip地址获取inet对象
        InetAddress inet2=InetAddress.getByName("3MD7Z093R6DTXXI");
        //InetAddress inet3=InetAddress.getByAddress("192.168.1.111", null);
        System.out.println(inet2);
        //获取主机名
        System.out.println(inet2.getHostName());
        //获取ip地址
        System.out.println(inet2.getHostAddress());
    }
package com.orcle.demo03;

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

public class UDPRecieve {
//接收端
    public static void main(String[] args) throws IOException {
        //创建scoket对象,明确端口号
        DatagramSocket ds=new DatagramSocket(6666);
        //创建字节数组,用来接收数据
        byte[] bytes=new byte[1024];
        while(true){
        
            //创建数据包对象
            DatagramPacket dp=new DatagramPacket(bytes, bytes.length);
            //接收数据
            ds.receive(dp);
            //拆包
            //获取数据长度
            int length=dp.getLength();
            //获取发送端的ip地址
            String ip=dp.getAddress().getHostAddress();
            //获取端口号
            int port=dp.getPort();
            System.out.println("ip地址为"+ip+",端口号为"+port+",发送的内容为:"+
                    new String(bytes,0,length));
        }
        //释放资源
        //ds.close();

    }

}
package com.orcle.demo03;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

public class UDPsend {
//发送端
    public static void main(String[] args) throws IOException {
        //创建socket对象
        DatagramSocket ds=new DatagramSocket();
        Scanner sc=new Scanner(System.in);
        while(true){
            //创建数据包对象,封装要发送的数据,以及明确接收端的IP和端口号
            byte[] bytes=sc.next().getBytes();
            //本机:   127.0.0.1  
            InetAddress inet=InetAddress.getByName("192.168.1.172");
            DatagramPacket dp=new DatagramPacket(bytes, bytes.length,inet,6666);
            //发送数据包对象
            ds.send(dp);
        }
        //释放资源
        //ds.close();
    }
}

 

posted @ 2020-04-26 22:29  龙茗夜雨  阅读(143)  评论(0编辑  收藏  举报