栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2021-10-30 Java学习(网络编程)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-30 Java学习(网络编程)

文章目录
  • 一、InetAddress类
  • 二、实现TCP的网络编程
    • 客户端发送内容给服务端,服务端将内容打印到控制台上
    • 客户端发送文件给服务端,服务端将文件保存在本地
    • 从客户端发送文件给服务端,服务端保存到本地,并返回“发送成功”给客户端,并关闭相应连接
  • 三、UDP网络编程
  • 四、URL编程

一、InetAddress类
import java.net.InetAddress;
import java.net.UnknownHostException;

//实例化InetAddress的两个方法:getByName(String host),getLocalHost()

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            InetAddress inet1=InetAddress.getByName("192.168.10.14");
            System.out.println(inet1);
            InetAddress inet2=InetAddress.getByName("www.atguigu.com");
            System.out.println(inet2);

            InetAddress local=InetAddress.getLocalHost();
            System.out.println(local);
            //两个常用方法
            //getHostName 获取域名
            System.out.println(inet2.getHostName());
            //getHostAddress 获取ip
            System.out.println(inet2.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

二、实现TCP的网络编程 客户端发送内容给服务端,服务端将内容打印到控制台上

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPtest {
    
    @Test
    public void client()  {
        Socket socket= null;
        OutputStream os= null;
        try {
            InetAddress inet=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,88899);

            os = socket.getOutputStream();
            os.write("客户端".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null)
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        
    }
    
    @Test
    public void server()
    {
        try {
            ServerSocket ss=new ServerSocket(8889);

            Socket socket=ss.accept();//这个socket可以用来接收来自客户端的socket

            InputStream is=socket.getInputStream();
            //不建议这样写,可能有乱码     
//        byte[] buffer=new byte[20];
//        int len;
//        while ((len=is.read(buffer))!=-1)
//        {
//            String str=new String(buffer,0,len);
//            System.out.print(str);
//        }

            ByteArrayOutputStream 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 {
            //各种close
        }


    }
    
}

客户端发送文件给服务端,服务端将文件保存在本地
import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest2 {

    @Test
    public void client() throws IOException {
        Socket socket= null;
        OutputStream os= null;
        FileInputStream fis= null;
        try {
            InetAddress inet1=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet1,9091);

            os = socket.getOutputStream();

            fis = new FileInputStream(new File("a.jpg"));

            byte[] buffer=new byte[20];
            int len;

            while((len=fis.read(buffer))!=-1)
            {
                os.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fis.close();
            os.close();
            socket.close();
        }


    }

    @Test
    public void server() throws IOException {
        ServerSocket ss= null;
        InputStream is= null;
        FileOutputStream fos= null;
        try {
            ss = new ServerSocket(9091);
            Socket socket=ss.accept();

            //客户端传来的数据写入
            is = socket.getInputStream();

            //想要获得文件/或者说还要打印消息,要把得到的这些数据写出
            fos = new FileOutputStream(new File("b.jpg"));

            byte[] buffer=new byte[20];
            int len;
            while((len=is.read(buffer))!=-1)
            {
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            is.close();
            fos.close();
            ss.close();
        }



    }
}

从客户端发送文件给服务端,服务端保存到本地,并返回“发送成功”给客户端,并关闭相应连接

客户端在传输时候会阻塞进程,因此传输完文件需要:
//关闭数据的输出
socket.shutdownOutput();//不传输了要告知!!

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTest3 {

    @Test
    public void client() throws IOException {
        Socket socket= null;
        OutputStream os= null;
        FileInputStream fis= null;
        ByteArrayOutputStream baos=null;
        InputStream is=null;
        try {
            InetAddress inet1=InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet1,9091);

            os = socket.getOutputStream();

            fis = new FileInputStream(new File("a.jpg"));

            byte[] buffer=new byte[20];
            int len;

            while((len=fis.read(buffer))!=-1)
            {
                os.write(buffer,0,len);
            }
            //关闭数据的输出
            socket.shutdownOutput();//不传输了要告知!!
            is=socket.getInputStream();
            baos=new ByteArrayOutputStream();
            byte[] buffer2=new byte[20];
            int len2;

            while ((len=is.read(buffer2))!=-1)
            {
                baos.write(buffer,0,len);
            }



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fis.close();
            os.close();
            is.close();
            baos.close();
            socket.close();

        }


    }

    @Test
    public void server() throws IOException {
        ServerSocket ss= null;
        InputStream is= null;
        FileOutputStream fos= null;
        OutputStream os=null;
        try {
            ss = new ServerSocket(9091);
            Socket socket=ss.accept();

            //客户端传来的数据写入
            is = socket.getInputStream();

            //想要获得文件/或者说还要打印消息,要把得到的这些数据写出
            fos = new FileOutputStream(new File("b.jpg"));

            byte[] buffer=new byte[20];
            int len;
            while((len=is.read(buffer))!=-1)
            {
                fos.write(buffer,0,len);
            }


            os=socket.getOutputStream();
            os.write("已经收到".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            is.close();
            os.close();
            fos.close();
            ss.close();
        }



    }
}

三、UDP网络编程
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket=new DatagramSocket();
        //不用把发送方地址和接收方地址放到socket里,都是装在数据报里面(packet)

        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()));
        socket.close();

    }
}

四、URL编程

URL其实就是对应着网络中的一个资源
URL:统一资源定位符

<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
参数名=参数值1&参数名=参数值…

常用方法

import java.net.MalformedURLException;
import java.net.URL;

public class URLTest {
    public static void main(String[] args) {
        try {
            URL url=new URL("http://localhost:8080/examples/a.jpg");
            System.out.println(url.getProtocol());
            System.out.println(url.getHost());
            System.out.println(url.getPort());
            System.out.println(url.getPath());//路径名
            System.out.println(url.getFile());//文件名
            System.out.println(url.getQuery());//获取查询名
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        
    }
}

实现Tomcat服务端数据下载

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLTest1 {
    public static void main(String[] args) throws IOException {
        InputStream is=null;
        FileOutputStream fos=null;
        URLConnection urlConnection=null;
        try {
            URL url=new URL("http://hocalhost:8080/examples/a.jpg");
            //下载服务器上的图片到本机

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            is = urlConnection.getInputStream();
            fos=new FileOutputStream("day04\aa.jpg");//main方法路径对应的是工程
            byte[] buffer=new byte[20];
            int len;
            while((len=is.read(buffer))!=-1)
            {
                fos.write(buffer,0,len);
            }
            
            
            

        } catch (MalformedURLException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            is.close();
            fos.close();
            urlConnection.disconnect();
        }

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/358416.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号