Last active
September 7, 2023 09:46
-
-
Save joshlong/a70bac0390081fc613df431e4bbec991 to your computer and use it in GitHub Desktop.
this is a simple network service that reverses strings. I'm using it to test out Project Loom
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.demo; | |
import org.springframework.boot.ApplicationRunner; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
import org.springframework.context.annotation.Bean; | |
import java.io.ByteArrayOutputStream; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.nio.charset.StandardCharsets; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
/** | |
* simple reversing service. Use with: {@code curl https://www.wikipedia.org/ | nc 127.0.0.1 9090 } | |
*/ | |
@SpringBootApplication | |
public class ReversingServiceApplication { | |
@Bean | |
ApplicationRunner runner() { | |
var ex = Executors.newVirtualThreadPerTaskExecutor(); | |
var port = 9090; | |
var server = new Server(ex, port); | |
return args -> server.start(); | |
} | |
public static void main(String[] args) { | |
SpringApplication.run(ReversingServiceApplication.class, args); | |
} | |
} | |
class Server { | |
private final int port; | |
private final ExecutorService executor; | |
Server(ExecutorService executor, int port) { | |
this.port = port; | |
this.executor = executor; | |
} | |
private static void handleRequest(Socket socket, InputStream in, OutputStream out) throws Throwable { | |
try { | |
var next = -1; | |
var baos = new ByteArrayOutputStream(); | |
while ((next = in.read()) != -1) | |
baos.write(next); | |
var reversedBytes = new StringBuilder(baos.toString()) | |
.reverse() | |
.toString() | |
.getBytes(StandardCharsets.UTF_8); | |
out.write(reversedBytes); | |
} /// | |
finally { | |
socket.close(); | |
} | |
} | |
public void start() throws Exception { | |
try (var serverSocket = new ServerSocket(this.port)) { | |
while (true) { | |
var client = serverSocket.accept(); | |
var is = client.getInputStream(); | |
var os = client.getOutputStream(); | |
this.executor.submit(() -> { | |
try { | |
handleRequest(client, is, os); | |
}// | |
catch (Throwable e) { | |
throw new RuntimeException("there's been an exception in our service: " + e.getMessage()); | |
} | |
}); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment