美文网首页
TCP与UDP协议详解

TCP与UDP协议详解

作者: kjy_112233 | 来源:发表于2017-08-30 22:59 被阅读0次

    一、TCP

    TCP建立连接后,通信双方都可以进行数据的传输;在保证可靠性上,采用超时重传和捎带确认机制;在流量控制上,采用滑动窗口协议,协议中规定,对于窗口内未经确认的分组需要重传;在拥塞控制上,采用慢启动算法。
    TCP服务端工作代码

    private static final int TCP_SERVER_PORT = 2321;
        //创建一个ServerSocket对象
        ServerSocket serverSocket = null;
        private void initDataServer(){
            try{
                //TCP_SERVER_PORT为指定的绑定端口,为int类型
                serverSocket = new ServerSocket(TCP_SERVER_PORT);
                //监听连接请求
                Socket socket = serverSocket.accept();
                //写入读Buffer中、获取输入流
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //放入写buffer中、获取输出流
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                //读取接收信息转换为字符串
                String ingoingMsg = in.readLine() + System.getProperty("line.separator");
                //生成发送字符串
                String outgoingMsg = "goodbye from port" + TCP_SERVER_PORT +     System.getProperty("line.separator");
                //将发送字符串写入上面定义的BufferWriter中
                out.write(outgoingMsg);
                //刷新,发送
                out.flush();
                //关闭
                socket.close();
            } catch (InterruptedIOException e) {
                //超时错误
                e.printStackTrace();
                //IO异常
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(serverSocket != null){
                    try{
                        serverSocket.close();
                    }catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    

    TCP客户端代码

    public void initDataClient(){
            try{
                //初始化Socket,TCP_SERVER_PORT为指定端口,int类型
                Socket socket = new Socket("localhost", TCP_SERVER_PORT);
                //获取输入流
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                //获取输出流
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                //读取接收信息转换为字符串
                String ingoingMsg = in.readLine() + System.getProperty("line.separator");
                //生成输出内容
                String outMsg = "TCP connecting to" + TCP_SERVER_PORT +     System.getProperty("line.separator");
                //写入
                out.write(outMsg);
                //刷新,发送
                out.flush();
                //获取输入流
                String inMsg = in.readLine() + System.getProperty("line.separator");
                //关闭连接
                socket.close();
            }catch (UnknownHostException e){
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    二、UDP通信

    UDP不提供数据报分组、组装和数据报排序的特点,当报文发送之后是无法得知其是否安全完整到达。
    UDP服务端代码

    //接收的字节的大小,客户端发送的数据不能超过MAX_UDP_DATAGRAM_LEN
    byte[] IMsg = new byte[MAX_UDP_DATAGRAM_LEN];
    //实例化一个DatagramPacket类
    DatagramPacket dp = new DatagramPacket(IMsg, IMsg.length);
    //新建一个DatagramPacket类
    DatagramPacket ds = null;
    try{
      //UDP服务器监听的端口
      ds = new DatagramPacket(UDP_SERVER_PORT);
      //准备接收数据
      ds.receive(dp);
    } catch (SocketException e){
      e.printStackTrace();
    } catch (IOException e){
      e.printStackTrace();
    } finally {
      //如果ds对象不为空,则关闭ds对象
      if (da != null){
        ds.close();
      }
    }
    

    UDP客户端代码

    //定义需要发送的信息
    String udpMsg = "hello world from UDP client" + UDP_SERVER_PORT;
    //新建一个DatagramPacket类
    DatagramPacket ds = null;
    try{
      //初始化DatagramPacket对象
      ds = new DatagramPacket();
      InetAddress serverAddr = InetAddress.getByName("127.0.0.1");
      DatagramPacket dp;
      //初始化DatagramPacket对象
      dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
      //发送
      ds.send(dp);
    //Socket连接异常
    } catch (SocketException e){
      e.printStackTrace();
    //不能连接到主机
    } catch (UnknownHostException e){
      e.printStackTrace();
    //数据流异常
    } catch (IOException e){
      e.printStackTrace();
    //其他异常
    } catch (Exception e){
      e.printStackTrace();
    } finally {
      //如果ds对象不为空,则关闭ds对象
      if (ds != null){
        ds.close();
      }
    }
    

    相关文章

      网友评论

          本文标题:TCP与UDP协议详解

          本文链接:https://www.haomeiwen.com/subject/toqfjxtx.html