Java网络编程之入门篇

 更新时间:2021年09月13日 11:10:54   作者:威斯布鲁克.猩猩  
这篇文章主要介绍了Java网络编程入门,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一、网络基础

 

二、网络协议

 实现TCP的网络编程
 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
public class TCPTest1 {
    //客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            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();
                }
            }
        }
 
    }
    //服务端
    @Test
    public void server(){
        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.println(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());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            if(baos != null){
                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();
                }
            }
        }
    }
}
 实现TCP的网络编程
 例题2:客户端发送文件给服务端,服务端将文件保存在本地。
public class TCPTest2 {
    //这里异常处理的方式应该使用try-catch-finally
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream 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);
        }
        fis.close();
        os.close();
        socket.close();
    }
    //这里异常处理的方式应该使用try-catch-finally
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9090);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream 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);
        }
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}
 实现TCP的网络编程
 例题3:从客户端发送文件给服务端,服务端保存到本地,并返回"发送成功"给客户端。并关闭相应的连接
 
public class TCPTest3 {
    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream 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);
        }
        //服务区端给予客户端反馈
        OutputStream os1 = socket.getOutputStream();
        os.write("你好,美女,照片我以收到,非常漂亮!".getBytes());
        fis.close();
        os.close();
        socket.close();
        os1.close();
 
    }
    //这里异常处理的方式应该使用try-catch-finally
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9090);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //接受来自于服务器端的数据,并显示到控制台上
        InputStream is1 = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while((len1 = is1.read(buffer)) != -1){
            baos.write(buffer,0,len1);
        }
        System.out.println(baos.toString());
        fos.close();
        is.close();
        socket.close();
        ss.close();
        baos.close();
    }
}

UDP协议的网络编程
public class UDPTest {
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
 
        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
        socket.send(packet);
        socket.close();
    }
    @Test
    public void receiver() throws IOException {
        DatagramSocket 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()));
    }

URL类

  URL网络编程
  1.URL:统一资源定位符,对应着互联网的某一资源地址
  2.格式:
    http://localhost:8080/examples/beauty.jpg?username=Tom
    协议   主机名     端口号    资源地址       参数列表
 
public class URLTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
//            public String getProtocol()       获取该URL的协议名
            System.out.println(url.getProtocol());// http
//            public String getHost()           获取该URL的主机名
            System.out.println(url.getHost());//localhost
//            public String getPort()           获取该URL的端口号
            System.out.println(url.getPort());// 8080
//            public String getPath()           获取该URL的文件路径
            System.out.println(url.getPath());//examples/beauty.jpg
//            public String getFile()           获取该URL的文件名
            System.out.println(url.getFile());//examples/beauty.jpg?username=Tom
//            public String getQuery()          获取该URL的查询名
            System.out.println(url.getQuery());//username=Tom
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

到此这篇关于Java网络编程之入门篇的文章就介绍到这了,更多相关Java网络编程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于java中集合的概念(详解)

    基于java中集合的概念(详解)

    下面小编就为大家带来一篇基于java中集合的概念(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • SpringBoot带你实现一个点餐小程序

    SpringBoot带你实现一个点餐小程序

    有个小伙伴临时找到我,要开发一个点餐的系统,时间比较着急,给了2天的时间。马马虎虎的搞出来了,头发掉了一撮!下面介绍下本系统,感兴趣的小伙伴,可以参考开发下
    2022-07-07
  • Java IO之序列化与反序列化详解

    Java IO之序列化与反序列化详解

    这篇文章主要为大家介绍了Java IO之序列化与反序列化,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-01-01
  • 详解Java中Object 类的使用

    详解Java中Object 类的使用

    Java的Object 类是所有类的父类,也就是说 Java 的所有类都继承了 Object,本文主要来和大家讲讲Object 类的使用,感兴趣的可以了解一下
    2023-05-05
  • java虚拟机学习笔记基础篇

    java虚拟机学习笔记基础篇

    在本篇文章里小编给大家整理的是关于java虚拟机学习笔记的相关内容,分享了一些基础知识点,需要的朋友们参考下。
    2019-06-06
  • springboot集成KoTime的配置过程

    springboot集成KoTime的配置过程

    koTime是一个springboot项目性能分析工具,通过追踪方法调用链路以及对应的运行时长快速定位性能瓶颈,这篇文章主要介绍了springboot集成KoTime,需要的朋友可以参考下
    2022-06-06
  • JAVAEE中用Session简单实现购物车功能示例代码

    JAVAEE中用Session简单实现购物车功能示例代码

    本篇文章主要介绍了JAVAEE中用Session简单实现购物车功能示例代码,非常具有实用价值,需要的朋友可以参考下。
    2017-03-03
  • Java多线程Thread基础学习

    Java多线程Thread基础学习

    每一个正在执行的程序都是一个进程,资源只有一块,所以在同一时间段会有多个程序同时执行,但是在一个时间点上,只能由一个程序执行,多线程是在一个进程的基础之上的进一步划分,需要的朋友可以参考下
    2023-04-04
  • SpringBoot+MyBatis-Plus实现分页的项目实践

    SpringBoot+MyBatis-Plus实现分页的项目实践

    MyBatis-Plus是基于MyBatis的持久层增强工具,提供简化CRUD、代码生成器、条件构造器、分页及乐观锁等功能,极大简化了开发工作量并提高了开发效率,本文就来介绍一下SpringBoot+MyBatis-Plus实现分页的项目实践,感兴趣的可以了解一下
    2024-11-11
  • Java 数据结构算法Collection接口迭代器示例详解

    Java 数据结构算法Collection接口迭代器示例详解

    这篇文章主要为大家介绍了Java 数据结构算法Collection接口迭代器示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09

最新评论