TCP和UDP简单认识

TCP和UDP简单认识

TCP协议

TCP(Transmission Control Protocol,传输控制协议)是面向连接的、可靠字节流服务,也就是说,在收发数据前,必须和对方建立可靠的连接。(就类似打电话,必须要对方接起电话才能聊天)

三次握手

TCP的连接需要经过3次握手

  1. 客户端:我可以和你处对象吗?
  2. 服务端:可以呀
  3. 客户端:太好了

四次挥手

TCP连接的断开需要经过4次挥手

  1. 客户端:你太懒了,我要和你分手!
  2. 服务端:分就分,等我收拾完行李就各奔东西!
  3. 服务端:我已经收拾完了,我们分手了!
  4. 客户端:好

TCP发送接收信息代码示例

客户端
public class TcpClient {
    public static void main(String[] args) {
        Socket socket = null;
        Scanner scanner = null;
        OutputStream os = null;
        try {
            InetAddress inetAddress = InetAddress.getByName("localhost");
            scanner = new Scanner(System.in);
            while (true) {
                // 因为下面的shutdown导致socket里的shutOut=true,但是没有任何方法改成false,所以只能重新new...
                socket = new Socket(inetAddress, 8888);
                os = socket.getOutputStream();
                String msg = scanner.next();
                os.write(msg.getBytes());
                System.err.println("客户端发送的msg:" + msg);
                // 这里必须shutdown,否则因为客户端没断开写的操作,服务端就没开始读
                socket.shutdownOutput();
                if ("exit".equals(msg)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != scanner) {
                scanner.close();
            }
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

服务端
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            serverSocket = new ServerSocket(8888);
            int len;
            byte[] buffer = new byte[1024];
            while (true) {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                baos = new ByteArrayOutputStream();
                while (-1 != (len = is.read(buffer))) {
                    baos.write(buffer, 0, len);
                }
                String msg = baos.toString();
                System.err.println("服务端接收到的msg:" + msg);
                if ("exit".equals(msg)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != socket) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

UDP协议

UDP (User Datagram Protocol,用户数据报协议),是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种非连接传输层协议,提供面向事务的简单不可靠信息传送服务,传输数据之前源端和终端不建立连接,当它想传送时就简单地去抓取来自应用程序的数据,并尽可能快地把它扔到网络上,故也不安全

模拟男孩给女孩发送消息的代码示例

public class UdpBoy {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        Scanner scanner = null;
        try {
            datagramSocket = new DatagramSocket();
            InetAddress inetAddress = InetAddress.getByName("localhost");
            scanner = new Scanner(System.in);
            while (true) {
                String msg = scanner.next();
                byte[] data = msg.getBytes();
                DatagramPacket packet = new DatagramPacket(data, 0, data.length, inetAddress, 8888);
                datagramSocket.send(packet);
                if ("exit".equals(msg)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != scanner) {
                scanner.close();
            }
            if (null != datagramSocket) {
                datagramSocket.close();
            }
        }
    }
}
public class UdpGirl {
    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;
        try {
            datagramSocket = new DatagramSocket(8888);
            while (true) {
                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
                datagramSocket.receive(packet);
                String msg = new String(packet.getData());
                System.err.println(msg);
                if ("exit".equals(msg)) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != datagramSocket) {
                datagramSocket.close();
            }
        }
    }
}

TCP和UDP对比

  1. TCP协议是一种有连接、可靠的、面向字节流、相对比较慢、点对点的传输层协议。

    UDP协议是一种无连接,不可靠、面向数据报、速度比较快、可实现一对一,多对一的传输层协议。

  2. TCP协议适用于对可靠性要求比较高的场合。

    UDP协议适用于对实时性有要求的场合。因为UDP不保证可靠性,所以UDP也没有重传机制,也没有拥塞机制,它只是尽最大努力交付数据。

  3. TCP运行速度慢,效率低,占用系统资源多,易被攻击。

    UDP运行速度较快,比TCP安全。

参考博客

详解 TCP 连接的“ 三次握手 ”与“ 四次挥手 ”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值