Skip to content

Commit 12aad05

Browse files
network programming and reflection (#205)
* update tcp * update udp * update reflection
1 parent 77f8f4c commit 12aad05

File tree

8 files changed

+260
-100
lines changed

8 files changed

+260
-100
lines changed

src/main/java/com/examplehub/basics/network/SocketClient.java

+6-9
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,26 @@
88
public class SocketClient {
99
public static void main(String[] args) throws IOException {
1010
Socket clientSocket = new Socket("127.0.0.1", 6666);
11-
try (InputStream inputStream = clientSocket.getInputStream()) {
12-
try (OutputStream outputStream = clientSocket.getOutputStream()) {
13-
handle(inputStream, outputStream);
14-
}
11+
try (InputStream inputStream = clientSocket.getInputStream(); OutputStream outputStream = clientSocket.getOutputStream()) {
12+
handle(inputStream, outputStream);
1513
}
1614
clientSocket.close();
1715
System.out.println("disconnected.");
1816
}
1917

2018
private static void handle(InputStream inputStream, OutputStream outputStream)
21-
throws IOException {
19+
throws IOException {
2220
var writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
2321
var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
2422
Scanner scanner = new Scanner(System.in);
2523
System.out.println("[server] " + reader.readLine());
2624
for (; ; ) {
27-
System.out.print(">>> "); // 打印提示
28-
String s = scanner.nextLine(); // 读取一行输入
25+
System.out.print(">>> ");
26+
String s = scanner.nextLine();
2927
writer.write(s + System.lineSeparator());
30-
// writer.newLine();
3128
writer.flush();
3229
String resp = reader.readLine();
33-
System.out.println("<<< " + resp);
30+
System.out.println("[server]: " + resp);
3431
if (resp.equals("bye")) {
3532
break;
3633
}

src/main/java/com/examplehub/basics/network/SocketServer.java

+15-9
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,30 @@
11
package com.examplehub.basics.network;
22

3+
import com.examplehub.strings.ReverseString;
4+
import com.examplehub.utils.StringUtils;
5+
36
import java.io.*;
47
import java.net.ServerSocket;
58
import java.net.Socket;
69
import java.nio.charset.StandardCharsets;
710

811
public class SocketServer {
912
static class ServerHandler implements Runnable {
10-
private Socket socket;
13+
private final Socket socket;
1114

1215
public ServerHandler(Socket socket) {
1316
this.socket = socket;
1417
}
1518

1619
public void run() {
17-
try (InputStream inputStream = this.socket.getInputStream()) {
18-
try (OutputStream outputStream = this.socket.getOutputStream()) {
19-
handle(inputStream, outputStream);
20-
}
20+
try (InputStream inputStream = this.socket.getInputStream();
21+
OutputStream outputStream = this.socket.getOutputStream()) {
22+
handle(inputStream, outputStream);
2123
} catch (Exception e) {
2224
try {
2325
this.socket.close();
2426
} catch (IOException ex) {
27+
ex.printStackTrace();
2528
}
2629
System.out.println("client disconnect");
2730
}
@@ -30,24 +33,27 @@ public void run() {
3033
private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
3134
var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
3235
var writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
33-
writer.write("hello!\n");
36+
writer.write("welcome connect service!\n");
3437
writer.flush();
3538
while (true) {
3639
String line = reader.readLine();
40+
System.out.println("[client]: " + line);
3741
if (line.equals("bye")) {
3842
writer.write("bye\n");
3943
writer.flush();
4044
break;
4145
}
42-
writer.write("ok: " + line + "\n");
46+
writer.write("ok: " + ReverseString.reverse(line) + "\n");
4347
writer.flush();
4448
}
4549
}
4650
}
4751

4852
public static void main(String[] args) throws IOException {
49-
ServerSocket serverSocket = new ServerSocket(6666);
50-
System.out.println("server is started!");
53+
int port = 6666;
54+
ServerSocket serverSocket = new ServerSocket(port);
55+
System.out.print("server is started! listen on: ");
56+
System.err.print(port);
5157
while (true) {
5258
Socket socket = serverSocket.accept();
5359
System.out.println("connected from " + socket.getRemoteSocketAddress());
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.examplehub.basics.network;
2+
3+
import java.io.IOException;
4+
import java.net.DatagramPacket;
5+
import java.net.DatagramSocket;
6+
import java.net.InetAddress;
7+
import java.nio.charset.StandardCharsets;
8+
9+
public class UDPClient {
10+
public static void main(String[] args) throws IOException {
11+
DatagramSocket datagramSocket = new DatagramSocket();
12+
byte[] buffer = "123".getBytes(StandardCharsets.UTF_8);
13+
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 6666);
14+
datagramSocket.send(datagramPacket);
15+
16+
byte[] bytes = new byte[1024];
17+
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
18+
datagramSocket.receive(dp);
19+
System.out.println("[server]: " + new String(bytes, 0, dp.getLength()));
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.examplehub.basics.network;
2+
3+
import com.examplehub.strings.ReverseString;
4+
5+
import java.io.IOException;
6+
import java.net.DatagramPacket;
7+
import java.net.DatagramSocket;
8+
import java.nio.charset.StandardCharsets;
9+
10+
public class UDPServer {
11+
public static void main(String[] args) throws IOException {
12+
int port = 6666;
13+
try(DatagramSocket datagramSocket = new DatagramSocket(port)) {
14+
System.out.println("server started! listen on: " + port);
15+
byte[] buffer = new byte[1024];
16+
DatagramPacket datagramPacket = new DatagramPacket(buffer, buffer.length);
17+
datagramSocket.receive(datagramPacket);
18+
System.out.println("[client]: " + new String(buffer, 0, datagramPacket.getLength()));
19+
20+
byte[] bytes = ReverseString.reverse(new String(buffer, 0, datagramPacket.getLength()))
21+
.getBytes(StandardCharsets.UTF_8);
22+
System.out.println(new String(bytes));
23+
DatagramPacket dp = new DatagramPacket(bytes, bytes.length, datagramPacket.getAddress(), datagramPacket.getPort());
24+
datagramSocket.send(dp);
25+
}
26+
}
27+
}

src/test/java/com/examplehub/basics/reflection/CreateObjFromClassTest.java

+85-3
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,93 @@
44

55
import org.junit.jupiter.api.Test;
66

7+
import java.lang.reflect.Constructor;
8+
import java.lang.reflect.InvocationTargetException;
9+
10+
class User {
11+
private String username;
12+
private int age;
13+
14+
public User() {
15+
}
16+
17+
public User(String username, int age) {
18+
this.username = username;
19+
this.age = age;
20+
}
21+
22+
public void setAge(int age) {
23+
this.age = age;
24+
}
25+
26+
public void setUsername(String username) {
27+
this.username = username;
28+
}
29+
30+
@Override
31+
public String toString() {
32+
return "User{" +
33+
"username='" + username + '\'' +
34+
", age=" + age +
35+
'}';
36+
}
37+
}
738
class CreateObjFromClassTest {
839
@Test
9-
void testCreateObj() throws InstantiationException, IllegalAccessException {
10-
Class cls = String.class;
11-
String str = (String) cls.newInstance();
40+
void testCreateObjUsingNewInstance() throws InstantiationException, IllegalAccessException {
41+
Class<String> cls = String.class;
42+
String str = cls.newInstance();
1243
assertTrue(str.isEmpty());
1344
}
45+
46+
@Test
47+
void testCreateCustomObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
48+
49+
Class<?> userClass = User.class;
50+
User user = (User) userClass.newInstance();
51+
user.setUsername("admin");
52+
user.setAge(25);
53+
assertEquals("User{username='admin', age=25}", user.toString());
54+
}
55+
56+
@Test
57+
void testCreateCustomObjectUsingConstructor() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
58+
Class<?> userClass = Class.forName("com.examplehub.basics.reflection.User");
59+
Constructor<?> constructor = userClass.getConstructor();
60+
assertEquals("public com.examplehub.basics.reflection.User()", constructor.toString());
61+
User user = (User) constructor.newInstance();
62+
user.setUsername("duyuanchao");
63+
user.setAge(25);
64+
assertEquals("User{username='duyuanchao', age=25}", user.toString());
65+
}
66+
67+
@Test
68+
void testCreateCustomObjectUsingConstructorWithArgs() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
69+
Class<?> userClass = Class.forName("com.examplehub.basics.reflection.User");
70+
Constructor<?> constructor = userClass.getConstructor(String.class, int.class);
71+
assertEquals("public com.examplehub.basics.reflection.User(java.lang.String,int)", constructor.toString());
72+
User user = (User) constructor.newInstance("duyuanchao", 26);
73+
assertEquals("User{username='duyuanchao', age=26}", user.toString());
74+
}
75+
76+
@Test
77+
void testGetAllConstructors() throws ClassNotFoundException {
78+
Class<?> userClass = Class.forName("com.examplehub.basics.reflection.User");
79+
Constructor<?>[] constructors = userClass.getConstructors();
80+
for (Constructor<?> constructor : constructors) {
81+
assertEquals(1, constructor.getModifiers());
82+
assertEquals("com.examplehub.basics.reflection.User", constructor.getName());
83+
Class<?>[] classes = constructor.getParameterTypes();
84+
int count = 0;
85+
for (Class<?> cls : classes) {
86+
if (count == 0) {
87+
assertEquals("java.lang.String", cls.getName());
88+
}
89+
if (count == 1) {
90+
assertEquals("int", cls.getName());
91+
}
92+
count++;
93+
}
94+
}
95+
}
1496
}

src/test/java/com/examplehub/basics/reflection/GetClassExampleTest.java

+39-9
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,48 @@
44

55
import org.junit.jupiter.api.Test;
66

7+
import java.time.Month;
8+
79
class GetClassExampleTest {
10+
11+
@Test
12+
void testVoid() {
13+
Class<Void> c = void.class;
14+
assertEquals("void", c.getName());
15+
assertEquals("void", c.getSimpleName());
16+
assertEquals("java.lang", c.getPackageName());
17+
assertEquals("void", c.toString());
18+
}
19+
820
@Test
921
void testGetClass() throws ClassNotFoundException {
10-
Class cls = String.class;
11-
Class cls2 = "hello".getClass();
12-
Class cls3 = Class.forName("java.lang.String");
13-
assertTrue(cls == cls2 && cls == cls3);
22+
Class<String> cls = String.class;
23+
Class<?> cls2 = "hello".getClass();
24+
Class<?> cls3 = Class.forName("java.lang.String");
25+
assertSame(cls, cls2);
26+
assertSame(cls, cls3);
27+
}
28+
29+
@Test
30+
void testGetClassByTYPE() {
31+
Class<?> c = Integer.TYPE;
32+
assertEquals("int", c.getName());
33+
assertEquals("int", c.getSimpleName());
34+
assertEquals("java.lang", c.getPackageName());
35+
assertEquals("int", c.toString());
36+
assertTrue(c.isPrimitive());
37+
}
38+
39+
@Test
40+
void testGetClassByClassloader() throws ClassNotFoundException {
41+
ClassLoader classLoader = GetClassExample.class.getClassLoader();
42+
Class<?> cls = classLoader.loadClass("java.lang.String");
43+
assertEquals("java.lang.String", cls.getName());
1444
}
1545

1646
@Test
1747
void testStringClass() {
18-
Class cls = "".getClass();
48+
Class<?> cls = "".getClass();
1949
assertEquals("java.lang.String", cls.getName());
2050
assertEquals("String", cls.getSimpleName());
2151
assertEquals("java.lang", cls.getPackageName());
@@ -27,7 +57,7 @@ void testStringClass() {
2757

2858
@Test
2959
void testInterface() {
30-
Class cls = Runnable.class;
60+
Class<Runnable> cls = Runnable.class;
3161
assertEquals("java.lang.Runnable", cls.getName());
3262
assertEquals("Runnable", cls.getSimpleName());
3363
assertEquals("java.lang", cls.getPackageName());
@@ -39,7 +69,7 @@ void testInterface() {
3969

4070
@Test
4171
void testMonth() {
42-
Class cls = java.time.Month.class;
72+
Class<Month> cls = java.time.Month.class;
4373
assertEquals("java.time.Month", cls.getName());
4474
assertEquals("Month", cls.getSimpleName());
4575
assertEquals("java.time", cls.getPackageName());
@@ -51,7 +81,7 @@ void testMonth() {
5181

5282
@Test
5383
void testStringArray() {
54-
Class cls = String[].class;
84+
Class<String[]> cls = String[].class;
5585
assertEquals("[Ljava.lang.String;", cls.getName());
5686
assertEquals("String[]", cls.getSimpleName());
5787
assertEquals("java.lang", cls.getPackageName());
@@ -63,7 +93,7 @@ void testStringArray() {
6393

6494
@Test
6595
void testPrimitive() {
66-
Class cls = int.class;
96+
Class<?> cls = int.class;
6797
assertEquals("int", cls.getName());
6898
assertEquals("int", cls.getSimpleName());
6999
assertEquals("java.lang", cls.getPackageName());

0 commit comments

Comments
 (0)