14.网络编程

1.InetAddress类的使用

一、网络编程中有两个主要问题:

​ 1.如何准确地定位网络上一台或多台主机:定位主机上的特定的应用

​ 2.找到主机后如何可靠高效地进行数据传输

二、网络编程中的两个要素

​ 1.IP和端口号

​ 2.提供网络通信协议:TCP/IP参考模型(应用层、传输层、网络层、数据链路层、物理层)

​ 3.IP分类:IPv4和IPv6;万维网和局域网

​ 4.域名:www.baidu.com(域名解析成IP然后建立连接)

​ 5.本地回路地址:127.0.0.1对应着localhost

InetAddress类:

​ 实例化InetAddress方法:getByName、getLocalHost

​ 两个常用方法:getHostName、getHostAddress

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

要求:不同进程有不同的端口号

范围:16位的整数 0—65535

端口号和IP地址的组合得出一个网络套接字:Socket

2.TCP网络编程

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

@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("你好,我是客户端".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //4.资源的关闭
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos= null;
        try {
            //1.创建服务器端的ServerSocket,知名自己的端口号
            serverSocket = new ServerSocket(8899);
            //2.调用accept方法表示接受来自于客户端的socket
            socket = serverSocket.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) {
            throw new RuntimeException(e);
        } finally {
            //5.资源关闭
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

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

@Test
public void client() throws IOException{
    //1.socket
    Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
    //2.获取输出流
    OutputStream os = socket.getOutputStream();
    //3.获取输入流
    FileInputStream fis=new FileInputStream(new File("编程背景.png"));
    //4.获取缓冲流
    BufferedInputStream bis = new BufferedInputStream(fis);
    //5.数据操作
    byte[] buffer=new byte[1024];
    int len;
    while((len=bis.read(buffer))!=-1){
        os.write(buffer,0,len);
    }
    //6.流的关闭
    os.close();
    bis.close();
    fis.close();
    socket.close();
}
@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("编程背景2.jpg"));
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    byte[] buffer=new byte[1024];
    int len;
    while((len=is.read(buffer))!=-1){
        bos.write(buffer,0,len);
    }
    bos.close();
    is.close();
    fos.close();
    socket.close();
    ss.close();
}

例题3:从客户端发送文件给服务端,服务端将文件保存本地,并返回“发送成功”给客户端

@Test
    public void client() throws IOException {
        //1.socket
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);//服务器的IP和端口
        //2.获取输出流
        OutputStream os = socket.getOutputStream();
        //3.获取输入流
        FileInputStream fis=new FileInputStream(new File("编程背景.png"));
        //4.获取缓冲流
        BufferedInputStream bis = new BufferedInputStream(fis);
        //5.数据操作
        byte[] buffer=new byte[1024];
        int len;
        while((len=bis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //关闭数据的输出
        socket.shutdownOutput();

        //6.接受来自于服务器端的数据,并显示在控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        byte[] buffer1=new byte[20];
        int len1;
        while((len1=is.read(buffer1))!=-1){
            baos.write(buffer1,0,len1);
        }
        System.out.println(baos);
//        InputStream is = socket.getInputStream();
//        InputStreamReader isr=new InputStreamReader(is);
//        char[] cbuf=new char[5];
//        int len1;
//        while((len1=isr.read(cbuf))!=-1){
//            String str=new String(cbuf,0,len1);
//            System.out.print(str);
//        }
        //7.流的关闭
//        isr.close();
        os.close();
        bis.close();
        fis.close();
        socket.close();
    }
    @Test
    public void server() throws IOException{
        //1.
        ServerSocket ss=new ServerSocket(9090);
        //2.
        Socket socket = ss.accept();
        //3.
        InputStream is = socket.getInputStream();
        //4.
        FileOutputStream fos=new FileOutputStream(new File("编程背景3.jpg"));
        //5.
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //6.
        byte[] buffer=new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            bos.write(buffer,0,len);
        }
        System.out.println("图片传输完成");
        //7.服务器端给予客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("你好,我已收到文件".getBytes());
        //8.
        bos.close();
        is.close();
        fos.close();
        socket.close();
        ss.close();
    }

3.UDP网络编程

实例

@Test
public void send() throws IOException {
    DatagramSocket socket = new DatagramSocket();

    String str="抽传统香烟,我测尼玛";
    byte[] data=str.getBytes();
    InetAddress inet=InetAddress.getByName("127.0.0.1");
    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[1024];
    DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
    socket.receive(packet);

    System.out.println(new String(packet.getData(),0,packet.getLength()));
}

4.URL编程

1.URL:统一资源定位符,对应着互联网的某一资源地址

2.格式

http://localhost:8080/examples/beauty.jpg?username=Tom

协议 主机号 端口号 资源地址 参数列表

3.实例化

URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
@Test
public void Test1(){
    HttpURLConnection urlConnection = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        is = urlConnection.getInputStream();
        fos = new FileOutputStream("beauty1.jpg");
        byte[] buffer=new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1) {
            fos.write(buffer,0,len);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        System.out.println("下载完成");
        if(fos!=null){
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        urlConnection.disconnect();
    }
();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        urlConnection.disconnect();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值