java之网络编程(TCP和UDP)

在接触网络编程前,首先要了解:

1、IP:Internet上计算机的唯一标识。

        分类:IPv4(万维网)和IPv6(局域网)

        本地Localhost对应的ip是:127.0.0.1

        域名解析:域名容易记忆,当在连接网络时输入一个主机的域名后,域名服务器(DNS)负责将域名转化成IP地址,这样才能和主机建立连接。

2、端口号:正在计算机上运行的进程

        ——不同的进程不同的端口号,范围0 ~  65535

3、InetAddress类:此类的一个对象就代表着一个具体的IP地址

        ——实例化:

getByName(String host)【在给定主机名的情况下确定主机的IP地址】

getLocalHost()【返回 主机名/IP】

        ——常用:getHostName()、getHostAddress()

TCP网络编程

发送信息:客户端发送信息给服务端,服务端将数据显示在控制台上。

客户端代码:

        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.14.100");
            socket = new Socket(inet,8899);
            //2.获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端mm".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源的关闭
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

服务端代码:

ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket
            socket = ss.accept();
            //3.获取输入流
            is = socket.getInputStream();

            //不建议这样写,可能会乱码
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = is.read(buffer)) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            //4.读取输入流中的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }

            System.out.println(baos.toString());

            System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(baos != null){
                //5.关闭资源
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

发送文件:客户端发送文件给服务端,服务端将文件保存在本地

客户端:

    Socket socket = null;
    OutputStream os = null;
    FileInputStream fis = null;
    
try{
    socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
    
    os = socket.getOutputStream();
    
    fis = new FileInputStream(new File("beauty.jpg"));
    
    byte[] buffer = new byte[1024];
    int len;
    while((len = fis.read(buffer)) != -1){
        os.write(buffer,0,len);
       }
}catch (IOException e) {
     e.printStackTrace();
    } finally {
            
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
    

服务端:

    ServerSocket ss = null;
    Socket socket = null;
    InputStream is = null;
    FileOutputStream fos;
        
try{
    ss = new ServerSocket(9090);
    
    socket = ss.accept();
    
    is = socket.getInputStream();
    
    fos = new FileOutputStream(new File("beauty1.jpg"));
    
    byte[] buffer = new byte[1024];
    int len;
    while((len = is.read(buffer)) != -1){
        fos.write(buffer,0,len);
    }
}catch (IOException e) {
            e.printStackTrace();
 } finally {
           
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
    }

关于socket.shutdownOutput():

1、在客户端或者服务端通过socket.shutdownOutput()都是单向关闭的,即关闭客户端的输出流并不会关闭服务端的输出流,所以是一种单方向的关闭流;
2、通过socket.shutdownOutput()关闭输出流,但socket仍然是连接状态,连接并未关闭
3、如果直接关闭输入或者输出流,即:in.close()或者out.close(),会直接关闭socket
————————————————
版权声明:本文为CSDN博主「zhuoni2013」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zhuoni2013/article/details/56494681

UDP网络编程:

发送端代码:

    DatagramSocket socket = null;
    
try{
    //建立数据码头
    socket = new DatagramSocket();
    
    //创建数据包
    String str = "我是UDP方式发送的导弹";
    //getBytes(StandardCharsets.Utf_8)能保证传输数据编码是UTF-8
    byte[] data = str.getBytes();
    InetAddress inet = InetAddress.getLocalHost();
    DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

    socket.send(packet);
}catch(IOException e) {
    e.printStackTrace();
 } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
}

接收端代码:

    DatagramSocket socket = null;
try{
    //建立数据码头
    socket = new DatagramSocket(9090);

    byte[] buffer = new byte[100];

    //接收数据包
    DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

    socket.receive(packet);
    
    //拆分数据包
    
    System.out.println(new String(packet.getData(),0,packet.getLength()));

}catch(IOException e) {
    e.printStackTrace();
 } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
}

TCP和UDP的区别

TCP三次握手和四次挥手

 

 

 ***(图片转自尚硅谷!)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值