Java网络编程

网络编程中两个主要的问题

  • 如何准确地定位网络上一台或多态主机;
  • 找到主机后如何可靠高效的进行数据传输

要素

  • IP和端口号
  • 提供网络通信协议: TCP/IP

IP端口号

  • IP:唯一的标识Internet计算机
    • Java中使用InetAddress类代表IP
    /**
     * 常用方法: InetAddress.getHostName() // 得到域名
     * 		InetAddress.getAddress() // 得到地址
     * 
     * @param args
     */
    public static void main(String[] args) {
    	try {
            // 可以填写域名或IP地址
    	    InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com");
    		// 获取本机IP
    		InetAddress inetAddress2 = InetAddress.getLocalHost();
    		System.out.println(inetAddress1);
    		System.out.println(inetAddress2);
    	} catch (UnknownHostException e) {
    		e.printStackTrace();
    	}
    }
    
    • IPv4、IPv6
  • 端口号:计算机上运行的进程
    • 不同的进程有不同的端口号
    • 范围: 0~65535
    • 分类:
      • 公认端口:0~1023。被预先定义的服务通信占用(HTTP占用80,FTP占用21,Telnet占用端口23)
      • 注册端口:1024~49151。分配给用户进程或应用程序。(如Tomcat占8080,Mysql占用3306,Oracle占用端口1521)
      • 动态/私有端口:491521~65535
  • 端口号与IP地址的组合得出一个网络套接字:Socket

网络通信协议

  • TCP
    • 使用TCP协议,先建立TCP连接,形成传输数据通道
    • 传输前,采用"三次握手"方式,点对点通信,是可靠的
    • TCP协议进行通信的两个应用进程: 客户端、服务端
    • 在连接中可进行大数据量的传输
    • 传输完毕,需要释放已建立的连接,效率低
    public class TCPTest1 {
    
        // 客户端
        @Test
        public void client() {
            Socket socket = null;
            OutputStream os = null;
            try {
                // 1.创建Socket对象,指明服务端的IP和端口号
                socket = new Socket(InetAddress.getLocalHost(), 8888);
                // 2.获取一个输出流,用于输出数据
                os = socket.getOutputStream();
                // 3.写出数据
                os.write("您好,服务器".getBytes());
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    // 关闭资源
                    if (os != null) {
                        os.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    
        // 服务器
        @Test
        public void server() {
            ServerSocket socket = null;
            Socket accept = null;
            InputStream iStream = null;
            ByteArrayOutputStream baoStream = null;
            try {
                // 1.创建服务器的ServerSocket,指明自己的端口号
                socket = new ServerSocket(8888);
                // 2.调用accept()方法,接受客户端数据
                accept = socket.accept();
                // 3. 获取输入流
                iStream = accept.getInputStream();
                // 可能会有乱码
                //byte[] buff = new byte[1024];
                //int len;
                //while ((len = iStream.read(buff)) != -1) {
                //System.out.println(new String(buff,0,len));
                //}
                // 4.读取输入流中的数据
                baoStream = new ByteArrayOutputStream();
                byte[] buff = new byte[1024];
                int len;
                while ((len = iStream.read(buff)) != -1) {
                    baoStream.write(buff, 0, len);
                }
                System.out.println(baoStream.toString());
                //得到客户端IP
                System.out.println(accept.getInetAddress().getHostAddress());
                System.out.println();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    // 5.关闭流
                    if (baoStream != null) {
                        baoStream.close();
                    }
                    if (iStream != null) {
                        iStream.close();
                    }
                    if (accept != null) {
                        accept.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
        /**
        * 客户端发送文件给服务端,服务端将文件保存在本地
        * 
        * @author Administrator
        *
        */
        public class TCPTest2 {
    
            // 客户端
            @Test
            public void client() {
                Socket socket = null;
                OutputStream os = null;
                BufferedInputStream bufferedInputStream = null;
                try {
                    // 1.创建Socket对象,指明服务端的IP和端口号
                    socket = new Socket(InetAddress.getLocalHost(), 8888);
                    // 2.获取一个输出流,用于输出数据
                    os = socket.getOutputStream();
                    // 3.写出数据
                    bufferedInputStream = new BufferedInputStream(new FileInputStream("1.jpg"));
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = bufferedInputStream.read(buff)) != -1) {
                        os.write(buff, 0, len);
                    }
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        // 关闭资源
                        if (os != null) {
                            os.close();
                        }
                        if (bufferedInputStream != null) {
                            bufferedInputStream.close();
                        }
                        if (socket != null) {
                            socket.close();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
            // 服务器
            @Test
            public void server() {
                ServerSocket socket = null;
                Socket accept = null;
                InputStream iStream = null;
                BufferedOutputStream baoStream = null;
                try {
                    // 1.创建服务器的ServerSocket,指明自己的端口号
                    socket = new ServerSocket(8888);
                    // 2.调用accept()方法,接受客户端数据
                    accept = socket.accept();
                    // 3. 获取输入流
                    iStream = accept.getInputStream();
                    // 4.读取输入流中的数据
                    baoStream = new BufferedOutputStream(new FileOutputStream(new File("2.jpg")));
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = iStream.read(buff)) != -1) {
                        baoStream.write(buff, 0, len);
                    }
                    // 得到客户端IP
                    System.out.println(accept.getInetAddress().getHostAddress());
                    System.out.println();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        // 5.关闭流
                        if (baoStream != null) {
                            baoStream.close();
                        }
                        if (iStream != null) {
                            iStream.close();
                        }
                        if (accept != null) {
                            accept.close();
                        }
                        if (socket != null) {
                            socket.close();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
    /**
        * 客户端发送文件给服务端,服务端将文件保存在本地,并返回"发送成功"给客户端
        * 
        * @author Administrator
        *
        */
        public class TCPTest2 {
    
            // 客户端
            @Test
            public void client() {
                Socket socket = null;
                OutputStream os = null;
                BufferedInputStream bufferedInputStream = null;
                ByteArrayOutputStream baoStream = null;
                try {
                    // 1.创建Socket对象,指明服务端的IP和端口号
                    socket = new Socket(InetAddress.getLocalHost(), 8888);
                    // 2.获取一个输出流,用于输出数据
                    os = socket.getOutputStream();
                    // 3.发送图片
                    bufferedInputStream = new BufferedInputStream(new FileInputStream("1.jpg"));
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = bufferedInputStream.read(buff)) != -1) {
                        os.write(buff, 0, len);
                    }
                    socket.shutdownOutput();
                    // 4.接受来自于服务器端的数据
                    InputStream is = socket.getInputStream();
                    baoStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int lens;
                    while ((lens = is.read(buffer)) != -1) {
                        baoStream.write(buffer, 0, lens);
                    }
    
                    System.out.println(baoStream.toString());
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        // 关闭资源
                        if (os != null) {
                            os.close();
                        }
                        if (bufferedInputStream != null) {
                            bufferedInputStream.close();
                        }
                        if (socket != null) {
                            socket.close();
                        }
                        if (baoStream != null) {
                            baoStream.close();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
    
            // 服务器
            @Test
            public void server() {
                ServerSocket socket = null;
                Socket accept = null;
                InputStream iStream = null;
                BufferedOutputStream baoStream = null;
                try {
                    // 1.创建服务器的ServerSocket,指明自己的端口号
                    socket = new ServerSocket(8888);
                    // 2.调用accept()方法,接受客户端数据
                    accept = socket.accept();
                    // 3. 获取输入流
                    iStream = accept.getInputStream();
                    // 4.读取输入流中的数据
                    baoStream = new BufferedOutputStream(new FileOutputStream(new File("2.jpg")));
                    byte[] buff = new byte[1024];
                    int len;
                    while ((len = iStream.read(buff)) != -1) {
                        baoStream.write(buff, 0, len);
                    }
                    // 5. 服务器端给予客户端反馈
                    OutputStream oStream = accept.getOutputStream();
                    oStream.write("发送成功".getBytes());
                    // 得到客户端IP
                    System.out.println(accept.getInetAddress().getHostAddress());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    try {
                        // 6.关闭流
                        if (baoStream != null) {
                            baoStream.close();
                        }
                        if (iStream != null) {
                            iStream.close();
                        }
                        if (accept != null) {
                            accept.close();
                        }
                        if (socket != null) {
                            socket.close();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    
  • UDP
    • 将数据、源、目的封装成数据包,不需要建立连接
    • 每个数据包的大小限制在64K内
    • 发送不管对方是否准备好,接收方收到也不确认
    • 可以广播发送
    • 发送数据结束时无需释放资源,开销小,速度快
    public class UDPTest {
    
        // 发送端
        @Test
        public void sender() {
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket();
                String str = "UDP";
                byte[] data = str.getBytes();
                InetAddress inet = InetAddress.getLocalHost();
                DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 8888);
                socket.send(packet);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    socket.close();
                }
            }
        }
    
        // 接收端
        @Test
        public void receiver() {
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket(8888);
                byte[] buff = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
                socket.receive(packet);
                System.out.println(new String(packet.getData(), 0, packet.getLength()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    socket.close();
                }
            }
        }
    }
    

URL

  • 简介: 统一资源定位符,表示Internet上某一资源的地址
  • 使用实例:
    @Test
	public void test() {
		try {
			URL url = new URL("https://www.baidu.com/img/bd_logo1.png?where=super");
			// 获取URL的协议名
			System.out.println(url.getProtocol()); 
			// 获取URL的主机名
			System.out.println(url.getHost()); 
			// 获取URL的端口号
			System.out.println(url.getPort()); 
			// 获取URL的文件路径
			System.out.println(url.getPath()); 
			// 获取URL的文件名
			System.out.println(url.getFile()); 
			// 获取URL的查询名
			System.out.println(url.getQuery()); 
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
    /**
     * 使用URL下载图片
     */
    @Test
	public void test() {
		BufferedOutputStream bufferedOutputStream = null;
		InputStream stream = null;
		HttpURLConnection urlConnection = null;
		try {
			URL url = new URL("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2157737149,3401931137&fm=26&gp=0.jpg");
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.connect();
			stream = urlConnection.getInputStream();
			bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File("3.jpg")));
			byte[] buffer = new byte[1024];
			int len;
			while ((len = stream.read(buffer)) != -1) {
				bufferedOutputStream.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (urlConnection != null) {
					urlConnection.disconnect();
				}
				if (stream != null) {
					stream.close();
				}
				if (bufferedOutputStream != null) {
					bufferedOutputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值