UDP通信,TCP通信

UDP发送端

  byte[] bytes="hello".getBytes();
       InetAddress inet=InetAddress.getByName("127.0.0.1");
       //明确传输内容,长度,目标地址,目标端口
       DatagramPacket dp=new DatagramPacket(bytes,bytes.length,inet,8888);
       DatagramSocket ds=new DatagramSocket(); //创建DatagramSocket对象,负责发送数据包
       ds.send(dp);//发送包
       ds.close();

UDP接收端

DatagramSocket ds=new DatagramSocket(8888);//端口号
        byte[] bytes=new byte[1024];
        DatagramPacket dp=new DatagramPacket(bytes,bytes.length);
        //dp传给ds接数据
        ds.receive(dp);
        //getAddress()获取为inet对象
        String ip=dp.getAddress().getHostAddress();//拆包,先获取Inet对象
        String host=dp.getAddress().getHostName();
        int port=dp.getPort();
        byte[] data=dp.getData();
        int length=dp.getLength();
        ds.close();

TCP客户端

        Socket socket=new Socket("127.0.0.1",6666);//创建socket,明确目标ip,端口
        //从socket对象中获取字节输出流.将数据写向服务器
        OutputStream out=socket.getOutputStream();
        out.write("你好".getBytes());  
        //接收回应
        //获取字节输入流,接收服务器端的响应数据
        InputStream in=socket.getInputStream();
        byte[] bytes=new byte[1024];
        int len=in.read(bytes);
        System.out.println(new String(bytes,0,len));  
        socket.close();

TCP服务端

        ServerSocket server=new ServerSocket(6666);//创建ServerSocket对象,明确端口号
        //与客户端创建连接并获取客户端对象
        Socket socket=server.accept();
        //字节输入流
        InputStream in=socket.getInputStream();
        byte[] bytes=new byte[1024];
        int len=in.read(bytes);
        System.out.println(new String(bytes,0,len));
        //给客户端返回响应
        //获取字节输出流
        OutputStream out=socket.getOutputStream();
        out.write("收到".getBytes());
        server.close();

 

posted on 2019-10-26 15:54  流光若影  阅读(142)  评论(0编辑  收藏  举报