博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java学习——网络编程UDP
阅读量:4678 次
发布时间:2019-06-09

本文共 5922 字,大约阅读时间需要 19 分钟。

UDP

将数据及源和目的封装成数据包中,不需要建立连接

每个数据报的大小限制在64k内

因无连接,是不可靠协议

不需要建立连接,速度快

TCP

建立连接,形成传输数据的通道

在连接中进行大数据量传输

通过三次握手完成连接,是可靠协议

必须建立连接,效率会稍低 

Ip获取:

import java.net.InetAddress;import java.net.UnknownHostException;public class IPDemo {    public static void main(String[] args) throws UnknownHostException {        //获取本地主机ip地址对象。         InetAddress ip = InetAddress.getLocalHost();                //获取其他主机的ip地址对象。        ip = InetAddress.getByName("192.168.1.110");        //ip = InetAddress.getByName("my_think");        //ip = InetAddress.getByName("www.baidu.com");                System.out.println(ip.getHostAddress());        System.out.println(ip.getHostName());    }}
View Code

 UDP协议发送端

* 创建UDP传输的发送端。

* 思路:
* 1,建立udp的socket服务。
* 2,将要发送的数据封装到数据包中。
* 3,通过udp的socket服务将数据包发送出去。
* 4,关闭socket服务。

public class UDPSendDemo {    public static void main(String[] args) throws IOException {        System.out.println("发送端启动......");           //1,udpsocket服务。使用DatagramSocket对象。        DatagramSocket ds = new DatagramSocket(8888);                //2,将要发送的数据封装到数据包中。        String str = "udp传输演示:哥们来了!";            //使用DatagramPacket将数据封装到的该对象包中。        byte[] buf = str.getBytes();                DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10000);                //3,通过udp的socket服务将数据包发送出去。使用send方法。        ds.send(dp);                //4,关闭资源。        ds.close();        }}
View Code

  UDP协议接收端

* 建立UDP接收端的思路。

* 1,建立udp socket服务,因为是要接收数据,必须要明确一个端口号。
* 2,创建数据包,用于存储接收到的数据。方便用数据包对象的方法解析这些数据.
* 3,使用socket服务的receive方法将接收的数据存储到数据包中。
* 4,通过数据包的方法解析数据包中的数据。
* 5,关闭资源

public class UDPReceDemo {    public static void main(String[] args) throws IOException {        System.out.println("接收端启动......");                        //1,建立udp socket服务。        DatagramSocket ds = new DatagramSocket(10000);                    //2,创建数据包。        byte[] buf = new byte[1024];        DatagramPacket dp = new DatagramPacket(buf,buf.length);                //3,使用接收方法将数据存储到数据包中。        ds.receive(dp);//阻塞式的。                //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。        String ip = dp.getAddress().getHostAddress();        int port = dp.getPort();        String text = new String(dp.getData(),0,dp.getLength());                System.out.println(ip+":"+port+":"+text);                //5,关闭资源。        ds.close();            }}
View Code

 对上述发送端接收端做简单修改,控制台进行输入

Send:

public class UDPSendDemo2 {    public static void main(String[] args) throws IOException {        System.out.println("发送端启动......");        DatagramSocket ds = new DatagramSocket(8888);    //        String str = "udp传输演示:哥们来了!";        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));        String line = null;                while((line=bufr.readLine())!=null){                    byte[] buf = line.getBytes();            DatagramPacket dp =                     new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.100"),10000);            ds.send(dp);                        if("886".equals(line))                break;        }                //4,关闭资源。        ds.close();        }}
View Code

Receive:

public class UDPReceDemo2 {    public static void main(String[] args) throws IOException {        System.out.println("接收端启动......");        //1,建立udp socket服务。        DatagramSocket ds = new DatagramSocket(10000);                while(true){            //2,创建数据包。        byte[] buf = new byte[1024];        DatagramPacket dp = new DatagramPacket(buf,buf.length);                //3,使用接收方法将数据存储到数据包中。        ds.receive(dp);//阻塞式的。                //4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。        String ip = dp.getAddress().getHostAddress();        int port = dp.getPort();        String text = new String(dp.getData(),0,dp.getLength());                System.out.println(ip+":"+port+":"+text);        }        //5,关闭资源。//        ds.close();            }}
View Code

UDP-简单聊天程序:

ChatDemo:

public class ChatDemo {    public static void main(String[] args) throws IOException {            DatagramSocket send = new DatagramSocket();            DatagramSocket rece = new DatagramSocket(10001);        new Thread(new Send(send)).start();        new Thread(new Rece(rece)).start();        }}
View Code

Receive:

public class Rece implements Runnable {    private DatagramSocket ds;    public Rece(DatagramSocket ds) {        this.ds = ds;    }    @Override    public void run() {        try {            while (true) {                // 2,创建数据包。                byte[] buf = new byte[1024];                DatagramPacket dp = new DatagramPacket(buf, buf.length);                // 3,使用接收方法将数据存储到数据包中。                ds.receive(dp);// 阻塞式的。                // 4,通过数据包对象的方法,解析其中的数据,比如,地址,端口,数据内容。                String ip = dp.getAddress().getHostAddress();                int port = dp.getPort();                String text = new String(dp.getData(), 0, dp.getLength());                                System.out.println(ip + "::" + text);                if(text.equals("886")){                    System.out.println(ip+"....退出聊天室");                }            }        } catch (Exception e) {}    }}
View Code

Send:

public class Send implements Runnable {    private DatagramSocket ds;        public Send(DatagramSocket ds){        this.ds = ds;    }    @Override    public void run() {            try {            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));            String line = null;                    while((line=bufr.readLine())!=null){                byte[] buf = line.getBytes();                DatagramPacket dp =                         new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.255"),10001);                ds.send(dp);                                if("886".equals(line))                    break;            }            ds.close();        } catch (Exception e) {}    }}
View Code

 

转载于:https://www.cnblogs.com/qinwangchen/p/5404823.html

你可能感兴趣的文章
C语言-常量指针与指针常量
查看>>
20145303 《Java程序设计》第7周学习总结
查看>>
Linux内核如何装载和启动一个可执行程序
查看>>
Socket网络编程--epoll小结
查看>>
数据库索引的实现原理
查看>>
32-3Sum
查看>>
用MySQL实现微博关注关系的方案分析
查看>>
99个Gmail邀请函
查看>>
android入门之: SharedPreferences
查看>>
C语言文件操作
查看>>
python文件结构与import用法
查看>>
c#汉字转拼音首字母全拼支持多音字
查看>>
学习总是无效,是因为你没有稳定的输出系统
查看>>
javaSe-反射2
查看>>
转iOS UIAppearance使用详解
查看>>
winform中实现label的自动换行
查看>>
MFC .。。CReBar 上添加工具栏背景
查看>>
人工智能浪潮下,岗位及就业,技术分析 _证券交易员
查看>>
hdu5705
查看>>
html学习文档-10、HTML 表格
查看>>