2021-08-11

This commit is contained in:
2021-08-11 18:08:06 +09:00
parent 5df880659e
commit 36c5ddbe9e
15 changed files with 515 additions and 2 deletions

14
network/build.gradle.kts Normal file
View File

@@ -0,0 +1,14 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
plugins {
id("elex-java")
}
dependencies {
}

20
network/logback.xml Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Examples for Java
~
~ Copyright (c) 2021. Elex. All Rights Reserved.
~ https://www.elex-project.com/
-->
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="TRACE">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@@ -0,0 +1,91 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.http;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@Slf4j
public class HttpSample {
public static void main(String... args) throws IOException {
requestGet();
}
public static void requestGet() throws IOException {
URL url = new URL("https://www.google.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setConnectTimeout(25000);
connection.setUseCaches(false);
// 연결
connection.connect();
// 응답 처리
System.out.println("STATUS: " + connection.getResponseCode());
connection.getHeaderFields().forEach((key, list) -> {
System.out.print(key + ": ");
list.forEach(item -> {
System.out.print(item + " ");
});
System.out.println();
});
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
reader.lines().forEachOrdered(line -> {
System.out.println(line);
});
}
connection.disconnect();
}
public static void requestPost() throws IOException {
URL url = new URL("https://www.google.com/");
byte[] data = "Hello".getBytes(StandardCharsets.UTF_8);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setFixedLengthStreamingMode(data.length);
connection.setConnectTimeout(25000);
connection.setUseCaches(false);
// 연결
connection.connect();
// 요청 바디 전송
OutputStream os = connection.getOutputStream();
os.write(data);
os.flush();
// 응답 처리
System.out.println("STATUS: " + connection.getResponseCode());
connection.getHeaderFields().forEach((key, list) -> {
System.out.print(key + ": ");
list.forEach(item -> {
System.out.print(item + " ");
});
System.out.println();
});
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
reader.lines().forEachOrdered(line -> {
System.out.println(line);
});
}
connection.disconnect();
}
}

View File

@@ -0,0 +1,36 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.multicast;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
@Slf4j
public class MulticastUdpClientSample {
public static void main(String... args) throws IOException {
MulticastSocket socket = new MulticastSocket(18888);
InetAddress group = InetAddress.getByName("224.0.0.1");
socket.joinGroup(group);
// 수신
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
log.info("Rx: {}", received);
socket.leaveGroup(group);
socket.close();
}
}

View File

@@ -0,0 +1,51 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.multicast;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.charset.StandardCharsets;
@Slf4j
public class MulticastUdpServerSample {
public static void main(String... args) throws IOException {
MulticastSocket socket = new MulticastSocket();
/*
IPv4 multicast addresses are defined by the leading address bits of 1110,
originating from the classful network design of the early Internet when this group of addresses
was designated as Class D. The Classless Inter-Domain Routing (CIDR) prefix of this group is 224.0.0.0/4.
The group includes the addresses from 224.0.0.0 to 239.255.255.255.
A multicast group is specified by a class D IP address and by a standard UDP port number.
Class D IP addresses are in the range 224.0.0.0 to 239.255.255.255, inclusive.
The address 224.0.0.0 is reserved and should not be used.
*/
for (int i = 0; i < 20; i++) {
// 발신
InetAddress group = InetAddress.getByName("224.0.0.1");
byte[] data = ("Hello~! " + i).getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(data, data.length, group, 18888);
socket.send(packet);
log.info("Tx: {}", new String(packet.getData()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Oops~!", e);
}
}
socket.disconnect();
}
}

View File

@@ -0,0 +1,44 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.new_http;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@Slf4j
public class Sample {
public static void main(String... args) throws IOException, InterruptedException {
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
// GET
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.google.com/"))
.header("X-Header", "Something")
.build();
HttpResponse<String> response = httpClient
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// POST
request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString("Hello"))
.uri(URI.create("https://www.examples.com/"))
.build();
response = httpClient
.send(request, HttpResponse.BodyHandlers.ofString());
}
}

View File

@@ -0,0 +1,24 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.socket;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.Socket;
@Slf4j
public class SocketClientSample {
public static void main(String... args) throws IOException {
Socket socket = new Socket("localhost", 18188);
// socket.getInputStream();
// socket.getOutputStream();
socket.close();
}
}

View File

@@ -0,0 +1,40 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.socket;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class SocketServerSample {
private List<Socket> clients = new ArrayList<>();
private ServerSocket socket;
public void open(int port) throws IOException {
socket = new ServerSocket(port);
while (!socket.isClosed()) {
try {
Socket client = socket.accept();
clients.add(client);
} catch (Throwable e) {
log.error("Oops!", e);
}
}
}
public static void main(String... args){
}
}

View File

@@ -0,0 +1,36 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.udp;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
@Slf4j
public class UdpClientSample {
public static void main(String... args) throws IOException {
DatagramSocket socket = new DatagramSocket();
//socket.
// 발신
byte[] buf = "Hi~ there.".getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(buf, buf.length,
InetAddress.getByName("localhost"), 18888);
socket.send(packet);
// 수신
buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
log.info("Rx: {}", received);
}
}

View File

@@ -0,0 +1,41 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.udp;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@Slf4j
public class UdpServerSample {
public static void main(String... args) throws IOException {
DatagramSocket socket = new DatagramSocket(18888);
// 수신
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
log.info("Rx: {}", new String(Arrays.copyOfRange(buf,packet.getOffset(),packet.getLength())));
// 발신
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] resp = "Hello~!".getBytes(StandardCharsets.UTF_8);
packet = new DatagramPacket(resp, resp.length, address, port);
socket.send(packet);
}
}

View File

@@ -0,0 +1,54 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples.url;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
@Slf4j
public class UrlSample {
public static void readFromUrl() throws IOException {
URL url = new URL("https://www.example.com/");
try (BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
//in.close();
}
}
public static void writeToUrl() throws IOException {
URL url = new URL("https://www.example.com/");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.connect();
try(OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
// write
out.write("Hello~");
// read
String inputLine;
while ((inputLine = in.readLine()) != null){
System.out.println(inputLine);
}
}
}
}

View File

@@ -0,0 +1,14 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ExecutorTest {
}

View File

@@ -12,5 +12,5 @@ include(
"ssh",
"web-socket-servlet", "web-socket-client",
"thread", "hibernate", "jdbc-sqlite",
"xml", "jackson", "jsoup", "markdown"
"xml", "jackson", "jsoup", "markdown", "network"
)

View File

@@ -0,0 +1,48 @@
/*
* Examples for Java
*
* Copyright (c) 2021. Elex. All Rights Reserved.
* https://www.elex-project.com/
*/
package kr.pe.elex.examples;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Synchronizing {
public static void main(String... args) {
final Rabbit rabbit = new Rabbit();
new Thread() {
@Override
public void run() {
rabbit.hello();
}
}.start();
new Thread() {
@Override
public void run() {
rabbit.count();
}
}.start();
new Thread() {
@Override
public void run() {
rabbit.hello();
}
}.start();
}
static class Rabbit {
public synchronized void count() {
for (int i = 0; i < 100; i++) {
System.out.println("Rabbit says " + i + ".");
}
}
public synchronized void hello() {
System.out.println("Rabbit says 'Hello'.");
}
}
}