网络编程
简单的socket使用例子(自己看用的)
//server端
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class server
{
public static class ak implements Runnable{
Socket sc=null;
public ak(Socket sc){
this.sc=sc;
}
@Override
public void run() {
System.out.println("server...");
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket=null;
int port=9999;
int counter=0;
serverSocket=new ServerSocket(port);
while(true){
Socket client=serverSocket.accept();
System.out.println("connect to client"+client);
counter++;
new Thread(new ak(client)).start();
}
}
}
//client端
import java.io.IOException;
import java.net.Socket;
public class client {
public static class ak implements Runnable{
Socket sc=null;
public ak(Socket sc){
this.sc=sc;
}
@Override
public void run() {
System.out.println("cilent...");
}
}
public static void main(String[] args) throws IOException {
String ip="127.0.0.1";
int port=9999;
Socket socket1=new Socket(ip,port);
Socket socket2=new Socket(ip,port);
new Thread(new ak(socket1)).start();
new Thread(new ak(socket2)).start();
}
}
junit测试
导入junit包后使用@Test启用
反射
以下是field使用的案例
//kibu.java
public class kibu {
public int a;
public int b;
private String c="sda";
@Override
public String toString() {
return "kibu{" +
"a=" + a +
", b=" + b +
'}';
}
}
//test.java
import java.lang.reflect.Field;
public class test {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class kibuClass=kibu.class;
//获取public修饰的成员变量
Field[] fields=kibuClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("---------");
//获取共有值,更改共有值
Field a=kibuClass.getField("a");
kibu kibu=new kibu();
Object value=a.get(kibu);
a.set(kibu,2);
System.out.println(kibu.toString());
System.out.println("==========");
//获取所有属性(包括私有)
Field[] declaredFields=kibuClass.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field);
}
//忽略安全检查,直接访问私有变量
Field d=kibuClass.getDeclaredField("c");
d.setAccessible(true); //暴力反射
Object value2=d.get(kibu);
System.out.println(value2);
}
}
注释
public class annotation {
//@Override 检测被注解标注的方法是否继承自父类(接口)的
//@Deprecated 该注解标识的内容,表示已经过时
//@SuppressWarnings 压制警告
@SuppressWarnings("all") //压制所有警告
public static void main(String[] args) {
}
}
JDBC
import java.sql.*;
public class jdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取数据库连接
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/testdata?serverTimezone=UTC","root","123456");
Statement stm=conn.createStatement();
ResultSet res= stm.executeQuery(
"select * from test"
);
while(res.next()){
System.out.println(res.getString(1));
}
}
}