网络编程 IP地址
概念:用于唯一标识网络中的每台计算机/主机
查看ip地址: ipconfig
ip地址的表示形式:点分十进制XX.XX.XX.XX
每一个十进制数的范围:0~255
ip地址的组成=网络地址+主机地址,比如:192.168.16.69
IPv6是互联网工程任务组设计的用于替代IPv4的下一代IP协议,其地址数量号称可以为全世界的每一粒沙子编上一个地址。
由于IPv4最大的问题在于网络地址资源有限,严重制约了互联网的应用和发展。IPv6的使用,不仅能解决网络地址资源数量的问题,而且也解决了多种接入设备连入互联网的障碍
ipv4地址分类
域名 将ip地址映射成域名(HTTP协议)
端口号
网络通信协议 TCP/IP(Transmission Control Protocol/Internet Protocol)的简写,中文译名为传输控制协议/因特网互联协议,又叫网络通讯协议,这个协议是lnternet最基本的协议、Internet国际互联网络的基础,简单地说,就是由网络层的IP协议和传输层的TCP协议组成的。
TCP和UDP
InetAddress类 1.获取本机InetAddress对象getLocalHost
2.根据指定主机名/域名获取ip地址对象getByName
3.获取InetAddress对象的主机名getHostName
4.获取InetAddress对象的地址getHostAddress
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.net.InetAddress;import java.net.UnknownHostException;public class API_ { public static void main (String[] args) throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); System.out.println(localHost); InetAddress host1 = InetAddress.getByName("DESKTOP-L57VJE8" ); System.out.println(host1); InetAddress host2 = InetAddress.getByName("www.baidu.com" ); System.out.println("host2=" + host2); String hostAddress = host2.getHostAddress(); System.out.println("host2 对应的ip = " + hostAddress); String hostName = host2.getHostName(); System.out.println("host2对应的主机名/域名=" + hostName); } }
Socket 1.套接字(Socket)开发网络应用程序被广泛采用,以至于成为事实上的标准。
2.通信的两端都要有Socket,是两台机器间通信的端点
3.网络通信其实就是Socket间的通信。
4.Socket允许程序把网络连接当成一个流,数据在两个Socket间通过IO传输。
5.一般主动发起通信的应用程序属客户端,等待通信请求的为服务端
TCP 网络通信编程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 import java.io.*;import java.net.InetAddress;import java.net.Socket;public class SocketTCP02Client { public static void main (String[] args) throws IOException { Socket socket = new Socket (InetAddress.getLocalHost(), 9999 ); BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream())); bw.write("hello,server" ); bw.newLine(); bw.flush(); socket.shutdownOutput(); BufferedReader br = new BufferedReader (new InputStreamReader (socket.getInputStream())); String line; while ((line = br.readLine()) != null ) { System.out.println(line); } br.close(); bw.close(); socket.close(); System.out.println("客户端退出..." ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class SocketTCP02Server { public static void main (String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket (9999 ); System.out.println("服务端,在9999端口监听,等待连接.." ); Socket socket = serverSocket.accept(); BufferedReader br = new BufferedReader (new InputStreamReader (socket.getInputStream())); String line; while ((line = br.readLine()) != null ) { System.out.println(line); } BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream())); bw.write("hello,client" ); bw.newLine(); bw.flush(); socket.shutdownOutput(); bw.close(); br.close(); socket.close(); serverSocket.close(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 import java.io.*;import java.net.ServerSocket;import java.net.Socket;public class TCPFileUploadServer { public static void main (String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket (8888 ); System.out.println("服务端在8888端口监听...." ); Socket socket = serverSocket.accept(); BufferedInputStream bis = new BufferedInputStream (socket.getInputStream()); byte [] bytes = StreamUtils.streamToByteArray(bis); String destFilePath = "src\\mg2.png" ; BufferedOutputStream bos = new BufferedOutputStream (new FileOutputStream (destFilePath)); bos.write(bytes); bos.close(); BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (socket.getOutputStream())); writer.write("收到图片" ); writer.flush(); socket.shutdownOutput(); writer.close(); bis.close(); socket.close(); serverSocket.close(); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.net.InetAddress;import java.net.Socket;public class TCPFileUploadClient { public static void main (String[] args) throws Exception { Socket socket = new Socket (InetAddress.getLocalHost(), 8888 ); String filePath = "D:\\Java_Project\\basicOfJava\\winsock_\\upload_\\mg.png" ; BufferedInputStream bis = new BufferedInputStream (new FileInputStream (filePath)); byte [] bytes = StreamUtils.streamToByteArray(bis); BufferedOutputStream bos = new BufferedOutputStream (socket.getOutputStream()); bos.write(bytes); bis.close(); socket.shutdownOutput(); InputStream inputStream = socket.getInputStream(); String s = StreamUtils.streamToString(inputStream); System.out.println(s); inputStream.close(); bos.close(); socket.close(); } }
netstat指令
UDP网络编程 1.类 DatagramSocket和 DatagramPacket[数据包/数据报]实现了基于UDP协议网络程序。
2.UDP数据报通过数据报套接字DatagramSocket发送和接收,系统不保证UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
3.DatagramPacket对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端的IP地址和端口号。
4.UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和接收方的连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPReceiverA { public static void main (String[] args) throws IOException { DatagramSocket socket = new DatagramSocket (9999 ); byte [] buf = new byte [1024 ]; DatagramPacket packet = new DatagramPacket (buf, buf.length); System.out.println("接收端A 等待接收数据.." ); socket.receive(packet); int length = packet.getLength(); byte [] data = packet.getData(); String s = new String (data, 0 , length); System.out.println(s); data = "好的, 明天见" .getBytes(); packet = new DatagramPacket (data, data.length, InetAddress.getByName("192.168.12.1" ), 9998 ); socket.send(packet); socket.close(); System.out.println("A端退出..." ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import java.io.IOException;import java.net.DatagramPacket;import java.net.DatagramSocket;import java.net.InetAddress;public class UDPSenderB { public static void main (String[] args) throws IOException { DatagramSocket socket = new DatagramSocket (9998 ); byte [] data = "hello 明天吃火锅~" .getBytes(); DatagramPacket packet = new DatagramPacket (data, data.length, InetAddress.getByName("192.168.12.1" ), 9999 ); socket.send(packet); byte [] buf = new byte [1024 ]; packet = new DatagramPacket (buf, buf.length); socket.receive(packet); int length = packet.getLength(); data = packet.getData(); String s = new String (data, 0 , length); System.out.println(s); socket.close(); System.out.println("B端退出" ); } }
反射 反射机制
Java 反射机制可以完成
在运行时判断任意一个对象所属的类
在运行时构造任意一个类的对象
在运行时得到任意一个类所具有的成员变量和方法
在运行时调用任意一个对象的成员变量和方法
生成动态代理
反射相关的主要类
java.lang.Class:代表一个类,Class对象表示某个类加载后在堆中的对象
java.lang.reflect.Method:代表类的方法,Method对象表示某个类的方法
java.lang.reflect.Field:代表类的成员变量, Field对象表示某个类的成员变量
java.lang.reflect.Constructor:代表类的构造方法,Constructor对象表示构造器
这些类在java.lang.reflection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 import java.io.FileInputStream;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Properties;public class Reflection01 { public static void main (String[] args) throws Exception { Properties properties = new Properties (); properties.load(new FileInputStream ("D:\\Java_Project\\basicOfJava\\reflection_\re.properties" )); String classfullpath = properties.get("classfullpath" ).toString(); String methodName = properties.get("method" ).toString(); Class cls = Class.forName(classfullpath); Object o = cls.newInstance(); System.out.println("o的运行类型=" + o.getClass()); Method method1 = cls.getMethod(methodName); System.out.println("=============================" ); method1.invoke(o); Field nameField = cls.getField("age" ); System.out.println(nameField.get(o)); Constructor constructor = cls.getConstructor(); System.out.println(constructor); Constructor constructor2 = cls.getConstructor(String.class); System.out.println(constructor2); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package reflection_;public class Cat { private String name = "招财猫" ; public int age = 10 ; public Cat () {} public Cat (String name) { this .name = name; } public void hi () { } public void cry () { System.out.println(name + " 喵喵叫.." ); } }
反射优点和缺点
1.优点:可以动态的创建和使用对象(也是框架底层核心),使用灵活,没有反射机制,框架技术就失去底层支撑。
2.缺点:使用反射基本是解释执行,对执行速度有影响.
反射调用优化-关闭访问检查
Method和Field、Constructor对象都有setAccessible(方法)
setAccessible作用是启动和禁用访问安全检查的开关
参数值为true表示反射的对象在使用时取消访问检查,提高反射的效率。参数值为false则表示反射的对象执行访问检查
Class类
Class也是类,因此也继承Object类
Class类对象不是new出来的,而是系统创建的
对于某个类的Class类对象,在内存中只有一份,因为类只加载一次
每个类的实例都会记得自己是由哪个Class 实例所生成
通过Class对象可以完整地得到一个类的完整结构,通过一系列API
Class对象是存放在堆的
类的字节码二进制数据,是放在方法区的,有的地方称为类的元数据(包括方法代码,变量名,方法名,访问权限等等)
Class 类的常用方法
获取 Class 类对象
如下类型有 Class 对象
类加载 反射机制是java实现动态语言的关键,也就是通过反射实现类动态加载。
1.静态加载:编译时加载相关的类,如果没有则报错,依赖性太强
2.动态加载:运行时加载需要的类,如果运行时不用该类,即使不存在该类,则不报错,降低了依赖性
1.当创建对象时(new)//静态加载
2.当子类被加载时,父类也加载//静态加载
3.调用类中的静态成员时//静态加载
4.通过反射//动态加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package reflection_.class_;public class ClassLoad03 { public static void main (String[] args) throws ClassNotFoundException { B b = new B (); } } class B { static { System.out.println("B 静态代码块被执行" ); num = 300 ; } static int num = 100 ; public B () { System.out.println("B() 构造器被执行" ); } }
通过反射获取类的结构信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 package reflection_;import org.junit.jupiter.api.Test;import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class ReflectionUtils { public static void main (String[] args) { } @Test public void api_02 () throws ClassNotFoundException, NoSuchMethodException { Class<?> personCls = Class.forName("reflection_.Person" ); Field[] declaredFields = personCls.getDeclaredFields(); for (Field declaredField : declaredFields) { System.out.println("本类中所有属性=" + declaredField.getName() + " 该属性的修饰符值=" + declaredField.getModifiers() + " 该属性的类型=" + declaredField.getType()); } Method[] declaredMethods = personCls.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { System.out.println("本类中所有方法=" + declaredMethod.getName() + " 该方法的访问修饰符值=" + declaredMethod.getModifiers() + " 该方法返回类型" + declaredMethod.getReturnType()); Class<?>[] parameterTypes = declaredMethod.getParameterTypes(); for (Class<?> parameterType : parameterTypes) { System.out.println("该方法的形参类型=" + parameterType); } } Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println("====================" ); System.out.println("本类中所有构造器=" + declaredConstructor.getName()); Class<?>[] parameterTypes = declaredConstructor.getParameterTypes(); for (Class<?> parameterType : parameterTypes) { System.out.println("该构造器的形参类型=" + parameterType); } } } @Test public void api_01 () throws ClassNotFoundException, NoSuchMethodException { Class<?> personCls = Class.forName("reflection_.Person" ); System.out.println(personCls.getName()); System.out.println(personCls.getSimpleName()); Field[] fields = personCls.getFields(); for (Field field : fields) { System.out.println("本类以及父类的属性=" + field.getName()); } Field[] declaredFields = personCls.getDeclaredFields(); for (Field declaredField : declaredFields) { System.out.println("本类中所有属性=" + declaredField.getName()); } Method[] methods = personCls.getMethods(); for (Method method : methods) { System.out.println("本类以及父类的方法=" + method.getName()); } Method[] declaredMethods = personCls.getDeclaredMethods(); for (Method declaredMethod : declaredMethods) { System.out.println("本类中所有方法=" + declaredMethod.getName()); } Constructor<?>[] constructors = personCls.getConstructors(); for (Constructor<?> constructor : constructors) { System.out.println("本类的构造器=" + constructor.getName()); } Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors(); for (Constructor<?> declaredConstructor : declaredConstructors) { System.out.println("本类中所有构造器=" + declaredConstructor.getName()); } System.out.println(personCls.getPackage()); Class<?> superclass = personCls.getSuperclass(); System.out.println("父类的class对象=" + superclass); Class<?>[] interfaces = personCls.getInterfaces(); for (Class<?> anInterface : interfaces) { System.out.println("接口信息=" + anInterface); } Annotation[] annotations = personCls.getAnnotations(); for (Annotation annotation : annotations) { System.out.println("注解信息=" + annotation); } } } class A { public String hobby; public void hi () { } public A () { } public A (String name) { } } interface IA {} interface IB {} @Deprecated class Person extends A implements IA , IB { public String name; protected static int age; String job; private double sal; public Person () { } public Person (String name) { } private Person (String name, int age) { } public void m1 (String name, int age, double sal) { } protected String m2 () { return null ; } void m3 () { } private void m4 () { } }
通过反射创建对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 package reflection_;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class ReflecCreateInstance { public static void main (String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, InvocationTargetException { Class<?> userClass = Class.forName("reflection_.User" ); Object o = userClass.newInstance(); System.out.println(o); Constructor<?> constructor = userClass.getConstructor(String.class); Object fzy = constructor.newInstance("fzy" ); System.out.println("fzy=" + fzy); Constructor<?> constructor1 = userClass.getDeclaredConstructor(int .class, String.class); constructor1.setAccessible(true ); Object user2 = constructor1.newInstance(100 , "张三丰" ); System.out.println("user2=" + user2); } } class User { private int age = 10 ; private String name = "Java学习" ; public User () { } public User (String name) { this .name = name; } private User (int age, String name) { this .age = age; this .name = name; } public String toString () { return "User [age=" + age + ", name=" + name + "]" ; } }
通过反射访问类中的成员 访问属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 import java.lang.reflect.Field;public class ReflecAccessProperty { public static void main (String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException { Class<?> stuClass = Class.forName("reflection_.Student" ); Object o = stuClass.newInstance(); System.out.println(o.getClass()); Field age = stuClass.getField("age" ); age.set(o, 88 ); System.out.println(o); System.out.println(age.get(o)); Field name = stuClass.getDeclaredField("name" ); name.setAccessible(true ); name.set(null , "老韩~" ); System.out.println(o); System.out.println(name.get(o)); System.out.println(name.get(null )); } } class Student { public int age; private static String name; public Student () { } public String toString () { return "Student [age=" + age + ", name=" + name + "]" ; } }
访问方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class ReflecAccessMethod { public static void main (String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { Class<?> bossCls = Class.forName("reflection_.Boss" ); Object o = bossCls.newInstance(); Method hi = bossCls.getDeclaredMethod("hi" , String.class); hi.invoke(o, "Java学习~" ); Method say = bossCls.getDeclaredMethod("say" , int .class, String.class, char .class); say.setAccessible(true ); System.out.println(say.invoke(o, 100 , "张三" , '男' )); System.out.println(say.invoke(null , 200 , "李四" , '女' )); Object reVal = say.invoke(null , 300 , "王五" , '男' ); System.out.println("reVal 的运行类型=" + reVal.getClass()); Method m1 = bossCls.getDeclaredMethod("m1" ); Object reVal2 = m1.invoke(o); System.out.println("reVal2的运行类型=" + reVal2.getClass()); } } class Monster {} class Boss { public int age; private static String name; public Boss () { } public Monster m1 () { return new Monster (); } private static String say (int n, String s, char c) { return n + " " + s + " " + c; } public void hi (String s) { System.out.println("hi " + s); } }