一、

网络编程的目的:
直接或间接地通过网络协议与其它计算机实现数据交换,进行通讯。

网络编程中有两个主要的问题:
如何准确地定位网络上一台或多台主机;定位主机上的特定的应用
找到主机后如何可靠高效地进行数据传输

二、网络通讯要素

IP和端口号
网络通信协议

三、IP和端口号

IP:InetAddress(java中的一个类代表网络IP地址)

端口号:标识正在计算机上运行的进程(程序)

  • 不同的进程有不同的端口号
  • 被规定为一个 16 位的整数 0~65535。
  • 端口分类:
    - 0~1023。被预先定义的服务通信占用(如:HTTP占用端口80,FTP占用端口21,Telnet占用端口23)
    - 注册端口:1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
    - 动态/私有端口:49152~65535

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

四、网络协议

1、网络通信协议

计算机网络中实现通信必须有一些约定,即通信协议,对速率、传输代码、代码结构、传输控制步骤、出错控制等制定标准。

问题:网络协议太复杂

通信协议分层的思想

2、TCP/IP协议簇

1)TCP协议

十四、网络编程-LMLPHP
十四、网络编程-LMLPHP

2)UDP

3、Socket

  • IP地址 + 端口号 = socket
  • 网络通信其实就是Socket间的通信,数据在socket之间通过io流传输

socket 分类
流套接字(stream socket):使用TCP提供可依赖的字节流服务
数据报套接字(datagram socket):使用UDP提供“尽力而为”的数据报服务

五、TCP网络编程

1、基于Socket的TCP编程

Java语言的基于套接字编程分为服务端编程客户端编程,其通信模型如图所示:
十四、网络编程-LMLPHP

1)客户端创建socket对象

    @Test
    public void client() {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet, 8899);
            outputStream = socket.getOutputStream();
            outputStream.write("你好,我是client".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                outputStream.close();
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

2) 服务器端建立 ServerSocket对象

  • ServerSocket 对象负责等待客户端请求建立套接字连接
  • 所谓“接收”客户的套接字请求,就是accept()方法会返回一个 Socket 对象
/**
 * 客户端将数据发送给服务端,服务端将数据显示在 控制台上
 */
public class TcpTest {


    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        try {
            serverSocket = new ServerSocket(8899);
            socket = serverSocket.accept();
            inputStream = socket.getInputStream();
            System.out.print("收到来自" + socket.getRemoteSocketAddress() + "的消息: ");
            byte[] buffer = new byte[20];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                String string = new String(buffer, 0, len);
                System.out.print(string);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            inputStream.close();
            socket.close();
            inputStream.close();
        }
    }
}

2、UDP网络通信

  • 类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。

  • UDP数据通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。

  • DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号

  • UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接。如同发快递包裹一样。

public class UdpTest {
    @Test
    public void client() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
            byte[] by = "hello,atguigu.com".getBytes();
            DatagramPacket dp = new DatagramPacket(by, 0, by.length, InetAddress.getByName("127.0.0.1"), 10000);
            ds.send(dp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ds.close();
        }
    }


    @Test
    public void server() {
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(10000);
            byte[] by = new byte[1024];
            DatagramPacket dp = new DatagramPacket(by, by.length);
            ds.receive(dp);
            String str = new String(dp.getData(), 0, dp.getLength());
            System.out.println(str + "--" + dp.getAddress());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) ds.close();
        }

    }
}

六、URL网络编程

1、URL类

URL(Uniform Resource Locator) 统一资源定位符,他表示Internet上某一资源的地址。

通过 URL 我们可以访问 Internet 上的各种网络资源,比如最常见的 www,ftp 站点。浏览器通过解析给定的 URL 可以在网络上查找相应的文件或其他资源。

URL的基本结构由5部分组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如:
http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
#片段名:即锚点,例如看小说,直接定位到章节
参数列表格式:参数名=参数值&参数名=参数值

URL的基本结构由5部分组成:
<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如:
http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
#片段名:即锚点,例如看小说,直接定位到章节
参数列表格式:参数名=参数值&参数名=参数值

为了表示URL,java.net 中实现了类 URL。我们可以通过下面的构造器来初始化一个 URL 对象:
十四、网络编程-LMLPHP

2、URLConnection类

URLConnection:表示到URL所引用的远程对象的连接。当与一个URL建立连接时,首先要在一个 URL 对象上通过方法 openConnection() 生成对应的 URLConnection对象。如果连接过程失败,将产生IOException。
URL netchinaren = new URL (“http://www.atguigu.com/index.shtml”);
URLConnectonn u = netchinaren.openConnection( );

通过URLConnection对象获取的输入流和输出流,即可以与现有的CGI程序进行交互。
public Object getContent( ) throws IOException
public int getContentLength( )
public String getContentType( )
public long getDate( )
public long getLastModified( )
public InputStream getInputStream( )throws IOException
public OutputSteram getOutputStream( )throws IOException

从服务器下载文件

public class URLTest1 {

    public static void main(String[] args) {

        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("day10\\beauty3.jpg");

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

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}

3、URI、URL、URN的区别

URI : uniform resource identifier 统一资源标识符,用来唯一的标识一个资源
URL: uniform resource locator 统一资源定位符,它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate这个资源。
URN:统一资源命名符,是通过名字来标识资源,比如mailto:java-net@java.sun.com。

05-04 00:31