Determine platform under JNA for setsockopt - java

I'm writing an implementation of setsockopt under JNA. Java itself supports setsockopt, but it doesn't support all the platform specific socket options. For instance, it doesn't support [TCP_KEEPIDLE][2] under Linux. Clearly, many of these options are not very portable, and using JNA is a route to poor portability; I am aware of this. Please don't bother to tell me the idea is deeply horrible.
What I'd like to do, however, is make my code a little more reuseable than something that just works under Linux. I'd like it to work (as far as is possible) on several target platforms. If the socket option is not available, it can throw an exception.
My challenge is this. The JNA works fine, but the values of the socket options are different across platforms. For instance, SO_RCVBUF is 0x1002 under OS-X and 8 under Linux (I realise SO_RCVBUF is controllable by the normal Java setSockOpt - it's an example that's easy to test with lsof). SO_DONTROUTE is 5 under Linux, and 0x0010 under OS-X (and that isn't controllable via Java setSockOpt).
So what I'd like it to do is to take an enum value representing the socket option (SO_SNDBUF, SO_RCVBUF or whatever), and look that up in a platform dependent map, so I get 0x1002 / 0x010 under OS-X and 8 / 5 under Linux.
That's easy enough, but how do I tell what the platform is under JNA so I know which map to use? JNA must somehow have a sense of its own platform, or it would not (I presume) know how to call the native libraries.
package sockettest;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.Socket;
import com.sun.jna.LastErrorException;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
public class JNASockOpt {
private static Field fdField;
static {
Native.register("c");
try {
fdField = FileDescriptor.class.getDeclaredField("fd");
fdField.setAccessible(true);
} catch (Exception ex) {
fdField = null;
}
}
public static int getInputFd(Socket s) {
try {
FileInputStream in = (FileInputStream)s.getInputStream();
FileDescriptor fd = in.getFD();
return fdField.getInt(fd);
} catch (Exception e) { }
return -1;
}
public static int getOutputFd(Socket s) {
try {
FileOutputStream in = (FileOutputStream)s.getOutputStream();
FileDescriptor fd = in.getFD();
return fdField.getInt(fd);
} catch (Exception e) { }
return -1;
}
public static int getFd(Socket s) {
int fd = getInputFd(s);
if (fd != -1)
return fd;
return getOutputFd(s);
}
// The list of SOL_ and SO_ options is platform dependent
public static final int SOL_SOCKET = 0xffff; // that's under OS-X, but it's 1 under Linux
public static final int SO_RCVBUF = 0x1002; // that's under OS-X, but it's 8 under Linux
public static final int SO_DONTROUTE = 0x0010; // that's under OS-X, but it's 5 under Linux
private static native int setsockopt(int fd, int level, int option_name, Pointer option_value, int option_len) throws LastErrorException;
public static void setSockOpt (Socket socket, int level, int option_name, int option_value) throws IOException {
if (socket == null)
throw new IOException("Null socket");
int fd = getFd(socket);
if (fd == -1)
throw new IOException("Bad socket FD");
IntByReference val = new IntByReference(option_value);
try {
setsockopt(fd, level, option_name, val.getPointer(), 4);
} catch (LastErrorException ex) {
throw new IOException("setsockopt: " + strerror(ex.getErrorCode()));
}
}
public static native String strerror(int errnum);
private JNASockOpt() {
}
}

The class com.sun.jna.Platform provided by JNA is used by JNA itself and has functions for querying the OS family and CPU architecture.
There are static methods for isMac() and isLinux().

jnaplatform does this by string parsing System.getProperty("os.name");, which seems pretty horrible to me, but if jnaplatform does it, I guess that should be good enough for me.
Results (i.e. how I used the above idea to solve the issue in the question) at https://github.com/abligh/jnasockopt - specifically https://github.com/abligh/jnasockopt/blob/master/src/org/jnasockopt/JNASockOptionDetails.java

Related

How can I get POSIX file descriptor in Java 11?

I have method, which using sun.misc.SharedSecrets.getJavaIOFileDescriptorAccess().get(FileDescriptor) by Java 8 for getting the real POSIX file descriptor. In Java 9 (and upper) SharedSecrets was migrated to jdk.internal.misc.
How can I get POSIX file descriptor in Java 11?
private int getFileDescriptor() throws IOException {
final int fd = SharedSecrets.getJavaIOFileDescriptorAccess().get(getFD());
if(fd < 1)
throw new IOException("failed to get POSIX file descriptor!");
return fd;
}
Thanks in advance!
This is only to be used in case of emergency (or until you find a different way since this is not supported) because it does things unintended by the API and is not supported. Caveat emptor.
package sandbox;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
public class GetFileHandle {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("somedata.txt")) {
FileDescriptor fd = fis.getFD();
Field field = fd.getClass().getDeclaredField("fd");
field.setAccessible(true);
Object fdId = field.get(fd);
field.setAccessible(false);
field = fd.getClass().getDeclaredField("handle");
field.setAccessible(true);
Object handle = field.get(fd);
field.setAccessible(false);
// One of these will be -1 (depends on OS)
// Windows uses handle, non-windows uses fd
System.out.println("fid.handle="+handle+" fid.fd"+fdId);
} catch (IOException | NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
}

JNA: Missing some specifics methods

I'm wanting create a dll injector in Java ( and only in Java ) for educational proporses for myself and found a basic example in a website especialized in online game.
The autor only said that was made using JNA interface.
So, i'm studyng this piece of code and trying compile with success using NetBeans IDE and JNA, but seem that JNA interface that i have here ( 4.2.2 ) not have all methods and functions used on piece of code left by autor.
Are they:
GetProcAddress
VirtualAllocEx
VirtualFreeEx
So, i'm wanting some help here if possible, for try solved this trouble of missing of methods in JNA.
I had fixed big part these erros but still missing some methods in JNA like i will show following point to point with comments.
package inject;
//////////////////// JNA-4.2.2 /////////////////////
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.platform.win32.WinNT.HANDLE;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.win32.W32APIOptions;
import java.io.File;
//////////////////////////////////////////////////
// Extracted from: https://github.com/warmuuh/AndroidCtx/tree/master/HotContext/src/luz/winapi
import inject.luz.winapi.constants.DwDesiredAccess;
import inject.luz.winapi.tools.Advapi32Tools;
import inject.luz.winapi.tools.Kernel32Tools;
import luz.winapi.api.exception.Kernel32Exception;
//////////////////////////////////////////////////////////////////////////////////////////////
public class Inject {
private static int GetPid(String proc){
int id = 0;
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (Native.toString(processEntry.szExeFile).equalsIgnoreCase(proc)) {
id = processEntry.th32ProcessID.intValue();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return id;
}
private static String findProcessByPID(int pid){
String name = "";
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);
Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
if (pid == processEntry.th32ProcessID.intValue()) {
name = processEntry.szExeFile.toString();
}
}
}
finally {
kernel32.CloseHandle(snapshot);
}
return name;
}
public static void inject(File dll, Integer pId) throws Kernel32Exception {
if(null == dll || !dll.exists() || !dll.isFile() || !dll.getName().endsWith(".dll"))
return;
String p = findProcessByPID(pId);
if(null == p) return;
Kernel32 kernel = Kernel32.INSTANCE;
HMODULE kernel32Pointer = kernel.GetModuleHandle("Kernel32");
// Cannot find "GetProcAddress"
Pointer loadLibraryAddress = kernel.GetProcAddress(kernel32Pointer, "LoadLibraryA");
HANDLE process = null;
DwDesiredAccess access = new DwDesiredAccess();
access.setPROCESS_ALL_ACCESS();
try {
Advapi32Tools.getInstance().enableDebugPrivilege(Kernel32Tools.getInstance().GetCurrentProcess());
} catch (Exception e) {
}
// Incompatible types "Pointer" and "HANDLE"
process = Kernel32Tools.getInstance().OpenProcess(access, false, pId);
String path = dll.getPath() + '\0';
byte[] bytes = path.getBytes();
int pathLength = bytes.length;
// Cannot find "VirtualAllocEx"
Pointer memoryDllPath = kernel.VirtualAllocEx(process, null, pathLength, Kernel32Tools.MEM_COMMIT, Kernel32Tools.PAGE_READWRITE);
Memory dllPathContent = new Memory(pathLength);
for(int i=0;i<pathLength;i++)
dllPathContent.setByte(i, bytes[i]);
IntByReference writeResult = new IntByReference();
boolean successWritting = kernel.WriteProcessMemory(process, memoryDllPath, dllPathContent, pathLength, writeResult);
if(!successWritting) {
kernel.CloseHandle(process);
return;
}
IntByReference threadId = new IntByReference();
// Pointer cannot be converted to "FOREIGN_THREAD_START_ROUTINE"
Pointer thread = kernel.CreateRemoteThread(process, null, 0, loadLibraryAddress, memoryDllPath, 0, threadId);
boolean res = false;
// Incompatible types "Pointer" and "HANDLE" //Cannot find "WAIT_TIMEOUT"
res = kernel.WaitForSingleObject(thread, Integer.MAX_VALUE) != Kernel32Tools.WAIT_TIMEOUT;
// Cannot find "VirtualFreeEx" method // Cannot find "MEM_RELEASE"
kernel.VirtualFreeEx(process, memoryDllPath, pathLength, Kernel32Tools.MEM_RELEASE);
kernel.CloseHandle(process);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println(GetPid("notepad.exe"));
}
}
Thank in advance by any suggestion or help :-)
JNA missing methods? It ain't so!
You just need to extend the library and add your own (and, ideally, also contribute the "missing" methods back to the JNA library so others can benefit.
Here is an example of how someone has mapped GetProcAddress.
Someone has mapped VirtualAllocEx here (although they should properly have extended Kernel32 rather than copied it entirely and edited portions)
I couldn't find an example of VirtualFreeEx within the same 15 seconds I found the others... doesn't mean it's not out there but after writing the others you shouldn't have much trouble writing it as well.

Passing Data from a Java program to a Python program and getting results back

What is the preferred way of passing data (a list of string) from a Java program to a Python script. The python script performs some processing on the data and then I need to get the results back in my Java program.
Is there is a framework that allows you to do this easily?
EDIT: More specific requirements.
My Java program is a scheduler (runs every X minutes and Y seconds ) that connects to an external service and gets the RAW data and send it to python.
I can rewrite everything in Python but that will take a me good amount of time. I was looking if there is a way to reuse what I already have.
I want to use an existing Python script with minimal change. My python script uses a bunch of external libraries (e.g., numpy)
The data passed from Java to Python is in Json format and the data returned by Python is also Json.
Using sockets is an options but then I've to run server processes.
I hacked this together a couple of months ago when I was faced with an similar problem. I avoided Jython because I wanted separate processes. The Java code is the server as it listens for requests but it doesn't re-connect on failure. The concept is is that the classes are extended threads that have a socket member so the send and receive commands can block the object threads and leave the host threads unaffected.
Python Code:
import StringIO
import re
import select
import socket
import sys
import threading
class IPC(threading.Thread):
def __init__(self, line_filter = None):
threading.Thread.__init__(self)
self.daemon = True
self.lock = threading.Lock()
self.event = threading.Event()
self.event.clear()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.recv_buffer_size = 8192
self.buffer = StringIO.StringIO()
if(line_filter == None):
self.line_filter = lambda x: x
else:
self.line_filter = line_filter
def run(self):
self.sock.connect(("localhost", 32000))
data = True
while data:
try:
data = self.sock.recv(self.recv_buffer_size)
except socket.error, e:
print e
self.sock.close()
break
self.lock.acquire()
self.buffer.write(data)
self.lock.release()
self.event.set()
def readlines(self):
self.lock.acquire()
self.buffer.seek(0)
raw_lines = self.buffer.readlines()
self.buffer.truncate(0)
self.lock.release()
lines = map(self.line_filter, raw_lines)
return lines
proc_control = IPC()
while True:
proc_control.event.wait()
data = proc_control.readlines()
if(data):
# Do Stuff
proc_control.event.clear()
Java Code:
SocketIPC.java:
package project;
import java.net.Socket;
import java.net.ServerSocket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class SocketIPC {
public PrintWriter out;
public BufferedReader in;
Socket socket = null;
ServerSocket serverSocket = null;
ConnectionListener connlisten = null;
DataListener datalisten = null;
Thread connlisten_thread = null;
Thread datalisten_thread = null;
CommandObject ipc_event_cmd = null;
// Server thread accepts incoming client connections
class ConnectionListener extends Thread {
private int port;
ConnectionListener(int port) {
this.port = port;
}
#Override
public void run() {
try {
serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
datalisten = new DataListener();
datalisten_thread = new Thread(datalisten);
datalisten_thread.start();
} catch (Exception e) {
System.err.println("SocketIPC creation error: " + e.getMessage());
}
}
}
// Server thread accepts incoming client connections
class DataListener extends Thread {
String data_str = null;
DataListener() {
}
#Override
public void run() {
try {
while(true) {
data_str = recv();
ipc_event_cmd.buffer.add(data_str);
ipc_event_cmd.execute();
}
} catch (Exception e) {
System.err.println("SocketIPC reading error: " + e.getMessage());
}
}
public String read() {
String ret_string = null;
if(!ipc_event_cmd.buffer.isEmpty()) {
ret_string = ipc_event_cmd.buffer.remove(0);
}
return ret_string;
}
}
public SocketIPC(int port) {
ipc_event_cmd = new CommandObject();
connlisten = new ConnectionListener(port);
connlisten_thread = new Thread(connlisten);
connlisten_thread.start();
}
public void send(String msg) {
if (out != null) {
out.println(msg);
}
}
public void flush() {
if (out != null) {
out.flush();
}
}
public void close() {
if (out != null) {
out.flush();
out.close();
try {
in.close();
socket.close();
serverSocket.close();
} catch (Exception e) {
System.err.println("SocketIPC closing error: " + e.getMessage());
}
}
}
public String recv() throws Exception {
if (in != null) {
return in.readLine();
} else {
return "";
}
}
public void set_cmd(CommandObject event_cmd) {
if (event_cmd != null) {
this.ipc_event_cmd = event_cmd;
}
}
}
CommandObject.java:
package project;
import java.util.List;
import java.util.ArrayList;
public class CommandObject {
List<String> buffer;
public CommandObject() {
this.buffer = new ArrayList<String>();
}
public void execute() {
}
}
DoStuff.java:
package project;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
public class DoStuff extends CommandObject {
public DoStuff () {
}
#Override
public void execute() {
String tmp_string = null;
while (!buffer.isEmpty()) {
tmp_string = buffer.remove(0);
// Do Stuff
}
}
}
Sounds like a job for Jython! Jython is an embeddedable Python runtime written in Java. As long as you don't need to run your Python script in another process (e.g., want to be able to kill it, may use lots of memory, etc.), this is the best way by far.
If you are trying to work Java and python together then make your life simple with Jython.
Jython, successor of JPython, is an implementation of the Python
programming language written in Java. Jython programs can import and
use any Java class. Except for some standard modules, Jython programs
use Java classes instead of Python modules. Jython includes almost all
of the modules in the standard Python programming language
distribution, lacking only some of the modules implemented originally
in C.
Assuming you have java lib in your python path. Here is a code snippet to give you an idea how simple it is to use the java classes:
'''
Import JavaUtilities class from a java package
'''
from com.test.javalib import JavaUtilities
'''
Call a java method
'''
response = JavaUtilities.doSomething();
Please have a look Jython,which is best for communication between java and Python.

Exchanging Object between client and server using sockets in java

I am trying to build an application where the server is a bank and the clients are the bracnhs of that bank so it's classic Multithread server / client app. In the first step i want the bank to record every branch that connects to it. so iwant to send the branck as object in the objectstream of the socket so that the bank can extract it and record it.
here's what i have done so far
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Banque {
private List<Succursale> listSucc = new ArrayList<Succursale>();
private int sommeTotale;
private int nbSuccInit = 4;
public void ajouteSucc(Succursale suc){
}
public Banque(){
initialiserServeur();
}
private void initialiserServeur() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10118);
}
catch (IOException e)
{
System.err.println("On ne peut pas ecouter au port: 10118.");
System.exit(1);
}
System.out.println ("Le serveur est en marche, Attente de la connexion.....");
int i = 0;
while(i<5){
try {
UtilMultiTh mt = new UtilMultiTh(serverSocket.accept());
Thread t = new Thread(mt);
t.start();
listSucc.add(mt.getSuc());
System.out.println(listSucc.size());
for(int j =0; j<listSucc.size();j++){
System.out.println("La succursale "+(j+1)+" est:"+listSucc.get(j).getName());
}
i++;
System.out.println("FLAGPOSTban");
}
catch (IOException e)
{
System.err.println("Accept a echoue.");
System.exit(1);
}
}
System.out.println ("connexion reussie");
System.out.println ("Attente de l'entree.....");
}
public static void main (String [] args){
Banque banK = new Banque();
}
}
The class MultiTh that manage the multi thread connection of the branchs
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.*;
public class UtilMultiTh implements Runnable {
private Socket soc;
private Succursale suc;
public UtilMultiTh(Socket s){
System.out.println("FLAGconsmth");
this.soc = s;
}
public void run() {
System.out.println("FLAGPOSrun");
ObjectOutputStream oos;
ObjectInputStream ois;
try{
oos = new ObjectOutputStream(soc.getOutputStream());
ois = new ObjectInputStream(soc.getInputStream());
//System.out.println("La succ est");
try {
Object o = ois.readObject();
if(o!=null){
suc = (Succursale)o;
//System.out.println("La succ est"+suc.getName());
}
/*while(o!=null){
suc = (Succursale)o;
System.out.println("La succ est"+suc.getName());
}*/
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
oos.close();
ois.close();
soc.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public synchronized Succursale getSuc() {
return suc;
}
public void setSuc(Succursale suc) {
this.suc = suc;
}
}
And here's the Succursale class for the branchs
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class Succursale implements Serializable {
private String coordonnees;
private String name;
private int sommeDepart;
private int sommeRecue;
private int sommeEnvoyee;
private List<Succursale> listSuccAc = new ArrayList<Succursale>();
private GuiSuccursale succView;
public Succursale (){
succView = new GuiSuccursale(Constantes.sommeDepart,1);
this.sommeDepart=Constantes.sommeDepart;
this.name="Succursale: "+(1);
connexionBanque();
}
public void connexionBanque(){
String host = Constantes.adrBanque[0];
int port = Constantes.portBanque[0];
Socket echoSocket = null;
try {
echoSocket = new Socket(host, port);
ObjectOutputStream oos = new ObjectOutputStream(echoSocket.getOutputStream());
oos.writeObject(this);
System.out.println("FLAGPOSTSUcc");
} catch (UnknownHostException e) {
System.err.println("Hôte inconnu: " + host);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Ne pas se connecter au serveur: " + host);
System.exit(1);
}
}
public void connexionSuccursales(){
}
public void envoiManuel(){
}
public String getName() {
return name;
}
public void envoiPeriodique(){
}
public static void main (String[] args){
Succursale suc = new Succursale();
}
}
I have two questions, how can i from the UtilMultuTh return a Succursale to Banque and before that why is that in the UtilMultiTh class readObject return null while in the succursale class just after etablishing the connection i put the class in the socket ? Do i have to put an infinite loop in here ?
EDIT: I changed the code, now multith is correctly getting the Succursale from the socket, the problem now is that the threads are no synchronised because UtilMultiTh gets the Succursale after Banque wants to get it, i am not familiar with synchrnosation, how can i tell Banque to do the getSuccursale only after utilMultiTh performed its run ?
Google's protobufs are perfect for this. I'd suggest using them and sending the byte output between client and server. You'll need to frame your output if you're planning to use TCP.
Java's serialization mechanism could always break between different runtime versions. Also, what if you decide to implement the server or client in another language? You'll have to duplicate java's entire serialization logic. Protobuf takes care of the tedious process required to marshall and unmarshall objects to and from bytes. So pretty much, its a better form of java's built in serialization which is language independent.
So I suggest you abandon Object streams. I know this isn't the answer you were hoping for, but it will make things nicer for you in the long run.
ProtoBuffers
This is not an answer to you question, but it won't fit in a comment and I think it needs to be said.
Be sure to reset your output stream after each write! ObjecdtOutputStream only writes an object once. If you try to write it again, it will just send a little note "Put that object I sent a while ago in back the input stream again at this point." Saves space, but if your object has changed, those changes won't get through. Also, the original object sent is going to be kept in memory on both sides, killing your performance. Reset clears everything out and gives you a fresh start.
Also, I'd use Externalizable rather than Serializable. This gives you control over what is sent (though you have to write some code). There is some danger that if you write an object that refers to other objects it will write all those other objects as well, which you may not want. Also, Externalizable lets you write to the same, old format even if the class changes. Also, it lets you put in version numbers. These can sometimes allow a newer version to read a stream written by an older version, but it always gives you a warning that the format has changed.
The intent of ObjectOutputStream is that you can write one object that includes all your data. A truly vast graph can be sent with one call to writeObject. This is ingenious. It worked fine for me, writing the complete state of a computer game to a disk file with one writeObject( this ), but it's usually a disaster when writing to a socket.
I am somewhat inclined not to use ObjectOutput, but to just write primitives. It's simpler and faster and you have a lot of control. But I have had trouble knowing which object to create on the Input end. I think the best thing to do is read and write objects, but keep the I/O simple by writing your own method for the Externalizable interface and calling reset() after each writeObject.

Simple HTTP server in Java using only Java SE API

Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses? The Java SE API nicely encapsulates the HTTP client functionality in HttpURLConnection, but is there an analog for HTTP server functionality?
Just to be clear, the problem I have with a lot of ServerSocket examples I've seen online is that they do their own request parsing/response formatting and error handling, which is tedious, error-prone, and not likely to be comprehensive, and I'm trying to avoid it for those reasons.
Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The Java 9 module name is jdk.httpserver. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.
Here's a kickoff example copypasted from their docs. You can just copy'n'paste'n'run it on Java 6+.
(to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source)
package com.stackoverflow.q3732109;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
#Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.
Execute it and go to http://localhost:8000/test and you'll see the following response:
This is the response
As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Moreover, this specific HttpServer must be present in every JDK so there is absolutely no means of "portability" issue like as would happen with sun.* package. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.
Check out NanoHttpd
NanoHTTPD is a light-weight HTTP server designed for embedding in other applications, released under a Modified BSD licence.
It is being developed at Github and uses Apache Maven for builds & unit testing"
The com.sun.net.httpserver solution is not portable across JREs. Its better to use the official webservices API in javax.xml.ws to bootstrap a minimal HTTP server...
import java.io._
import javax.xml.ws._
import javax.xml.ws.http._
import javax.xml.transform._
import javax.xml.transform.stream._
#WebServiceProvider
#ServiceMode(value=Service.Mode.PAYLOAD)
class P extends Provider[Source] {
def invoke(source: Source) = new StreamSource( new StringReader("<p>Hello There!</p>"));
}
val address = "http://127.0.0.1:8080/"
Endpoint.create(HTTPBinding.HTTP_BINDING, new P()).publish(address)
println("Service running at "+address)
println("Type [CTRL]+[C] to quit!")
Thread.sleep(Long.MaxValue)
EDIT: this actually works! The above code looks like Groovy or something. Here is a translation to Java which I tested:
import java.io.*;
import javax.xml.ws.*;
import javax.xml.ws.http.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
#WebServiceProvider
#ServiceMode(value = Service.Mode.PAYLOAD)
public class Server implements Provider<Source> {
public Source invoke(Source request) {
return new StreamSource(new StringReader("<p>Hello There!</p>"));
}
public static void main(String[] args) throws InterruptedException {
String address = "http://127.0.0.1:8080/";
Endpoint.create(HTTPBinding.HTTP_BINDING, new Server()).publish(address);
System.out.println("Service running at " + address);
System.out.println("Type [CTRL]+[C] to quit!");
Thread.sleep(Long.MAX_VALUE);
}
}
I like this question because this is an area where there's continuous innovation and there's always a need to have a light server especially when talking about embedded servers in small(er) devices. I think answers fall into two broad groups.
Thin-server: server-up static content with minimal processing, context or session processing.
Small-server: ostensibly a has many httpD-like server qualities with as small a footprint as you can get away with.
While I might consider HTTP libraries like: Jetty, Apache Http Components, Netty and others to be more like a raw HTTP processing facilities. The labelling is very subjective, and depends on the kinds of thing you've been call-on to deliver for small-sites. I make this distinction in the spirit of the question, particularly the remark about...
"...without writing code to manually parse HTTP requests and manually format HTTP responses..."
These raw tools let you do that (as described in other answers). They don't really lend themselves to a ready-set-go style of making a light, embedded or mini-server. A mini-server is something that can give you similar functionality to a full-function web server (like say, Tomcat) without bells and whistles, low volume, good performance 99% of the time. A thin-server seems closer to the original phrasing just a bit more than raw perhaps with a limited subset functionality, enough to make you look good 90% of the time. My idea of raw would be makes me look good 75% - 89% of the time without extra design and coding. I think if/when you reach the level of WAR files, we've left the "small" for bonsi servers that looks like everything a big server does smaller.
Thin-server options
Grizzly
UniRest (multiple-languages)
NanoHTTPD (just one file)
Mini-server options:
Spark Java ... Good things are possible with lots of helper constructs like Filters, Templates, etc.
MadVoc ... aims to be bonsai and could well be such ;-)
Among the other things to consider, I'd include authentication, validation, internationalisation, using something like FreeMaker or other template tool to render page output. Otherwise managing HTML editing and parameterisation is likely to make working with HTTP look like noughts-n-crosses. Naturally it all depends on how flexible you need to be. If it's a menu-driven FAX machine it can be very simple. The more interactions, the 'thicker' your framework needs to be. Good question, good luck!
Have a look at the "Jetty" web server Jetty. Superb piece of Open Source software that would seem to meet all your requirments.
If you insist on rolling your own then have a look at the "httpMessage" class.
Once upon a time I was looking for something similar - a lightweight yet fully functional HTTP server that I could easily embed and customize. I found two types of potential solutions:
Full servers that are not all that lightweight or simple (for an extreme definition of lightweight.)
Truly lightweight servers that aren't quite HTTP servers, but glorified ServerSocket examples that are not even remotely RFC-compliant and don't support commonly needed basic functionality.
So... I set out to write JLHTTP - The Java Lightweight HTTP Server.
You can embed it in any project as a single (if rather long) source file, or as a ~50K jar (~35K stripped) with no dependencies. It strives to be RFC-compliant and includes extensive documentation and many useful features while keeping bloat to a minimum.
Features include: virtual hosts, file serving from disk, mime type mappings via standard mime.types file, directory index generation, welcome files, support for all HTTP methods, conditional ETags and If-* header support, chunked transfer encoding, gzip/deflate compression, basic HTTPS (as provided by the JVM), partial content (download continuation), multipart/form-data handling for file uploads, multiple context handlers via API or annotations, parameter parsing (query string or x-www-form-urlencoded body), etc.
I hope others find it useful :-)
Spark is the simplest, here is a quick start guide: http://sparkjava.com/
All the above answers details about Single main threaded Request Handler.
setting:
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
Allows multiple request serving via multiple threads using executor service.
So the end code will be something like below:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class App {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
//Thread control is given to executor service.
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
server.start();
}
static class MyHandler implements HttpHandler {
#Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
long threadId = Thread.currentThread().getId();
System.out.println("I am thread " + threadId );
response = response + "Thread Id = "+threadId;
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
It's possible to create an httpserver that provides basic support for J2EE servlets with just the JDK and the servlet api in a just a few lines of code.
I've found this very useful for unit testing servlets, as it starts much faster than other lightweight containers (we use jetty for production).
Most very lightweight httpservers do not provide support for servlets, but we need them, so I thought I'd share.
The below example provides basic servlet support, or throws and UnsupportedOperationException for stuff not yet implemented. It uses the com.sun.net.httpserver.HttpServer for basic http support.
import java.io.*;
import java.lang.reflect.*;
import java.net.InetSocketAddress;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
#SuppressWarnings("deprecation")
public class VerySimpleServletHttpServer {
HttpServer server;
private String contextPath;
private HttpHandler httpHandler;
public VerySimpleServletHttpServer(String contextPath, HttpServlet servlet) {
this.contextPath = contextPath;
httpHandler = new HttpHandlerWithServletSupport(servlet);
}
public void start(int port) throws IOException {
InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
server = HttpServer.create(inetSocketAddress, 0);
server.createContext(contextPath, httpHandler);
server.setExecutor(null);
server.start();
}
public void stop(int secondsDelay) {
server.stop(secondsDelay);
}
public int getServerPort() {
return server.getAddress().getPort();
}
}
final class HttpHandlerWithServletSupport implements HttpHandler {
private HttpServlet servlet;
private final class RequestWrapper extends HttpServletRequestWrapper {
private final HttpExchange ex;
private final Map<String, String[]> postData;
private final ServletInputStream is;
private final Map<String, Object> attributes = new HashMap<>();
private RequestWrapper(HttpServletRequest request, HttpExchange ex, Map<String, String[]> postData, ServletInputStream is) {
super(request);
this.ex = ex;
this.postData = postData;
this.is = is;
}
#Override
public String getHeader(String name) {
return ex.getRequestHeaders().getFirst(name);
}
#Override
public Enumeration<String> getHeaders(String name) {
return new Vector<String>(ex.getRequestHeaders().get(name)).elements();
}
#Override
public Enumeration<String> getHeaderNames() {
return new Vector<String>(ex.getRequestHeaders().keySet()).elements();
}
#Override
public Object getAttribute(String name) {
return attributes.get(name);
}
#Override
public void setAttribute(String name, Object o) {
this.attributes.put(name, o);
}
#Override
public Enumeration<String> getAttributeNames() {
return new Vector<String>(attributes.keySet()).elements();
}
#Override
public String getMethod() {
return ex.getRequestMethod();
}
#Override
public ServletInputStream getInputStream() throws IOException {
return is;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
#Override
public String getPathInfo() {
return ex.getRequestURI().getPath();
}
#Override
public String getParameter(String name) {
String[] arr = postData.get(name);
return arr != null ? (arr.length > 1 ? Arrays.toString(arr) : arr[0]) : null;
}
#Override
public Map<String, String[]> getParameterMap() {
return postData;
}
#Override
public Enumeration<String> getParameterNames() {
return new Vector<String>(postData.keySet()).elements();
}
}
private final class ResponseWrapper extends HttpServletResponseWrapper {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final ServletOutputStream servletOutputStream = new ServletOutputStream() {
#Override
public void write(int b) throws IOException {
outputStream.write(b);
}
};
private final HttpExchange ex;
private final PrintWriter printWriter;
private int status = HttpServletResponse.SC_OK;
private ResponseWrapper(HttpServletResponse response, HttpExchange ex) {
super(response);
this.ex = ex;
printWriter = new PrintWriter(servletOutputStream);
}
#Override
public void setContentType(String type) {
ex.getResponseHeaders().add("Content-Type", type);
}
#Override
public void setHeader(String name, String value) {
ex.getResponseHeaders().add(name, value);
}
#Override
public javax.servlet.ServletOutputStream getOutputStream() throws IOException {
return servletOutputStream;
}
#Override
public void setContentLength(int len) {
ex.getResponseHeaders().add("Content-Length", len + "");
}
#Override
public void setStatus(int status) {
this.status = status;
}
#Override
public void sendError(int sc, String msg) throws IOException {
this.status = sc;
if (msg != null) {
printWriter.write(msg);
}
}
#Override
public void sendError(int sc) throws IOException {
sendError(sc, null);
}
#Override
public PrintWriter getWriter() throws IOException {
return printWriter;
}
public void complete() throws IOException {
try {
printWriter.flush();
ex.sendResponseHeaders(status, outputStream.size());
if (outputStream.size() > 0) {
ex.getResponseBody().write(outputStream.toByteArray());
}
ex.getResponseBody().flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
ex.close();
}
}
}
public HttpHandlerWithServletSupport(HttpServlet servlet) {
this.servlet = servlet;
}
#SuppressWarnings("deprecation")
#Override
public void handle(final HttpExchange ex) throws IOException {
byte[] inBytes = getBytes(ex.getRequestBody());
ex.getRequestBody().close();
final ByteArrayInputStream newInput = new ByteArrayInputStream(inBytes);
final ServletInputStream is = new ServletInputStream() {
#Override
public int read() throws IOException {
return newInput.read();
}
};
Map<String, String[]> parsePostData = new HashMap<>();
try {
parsePostData.putAll(HttpUtils.parseQueryString(ex.getRequestURI().getQuery()));
// check if any postdata to parse
parsePostData.putAll(HttpUtils.parsePostData(inBytes.length, is));
} catch (IllegalArgumentException e) {
// no postData - just reset inputstream
newInput.reset();
}
final Map<String, String[]> postData = parsePostData;
RequestWrapper req = new RequestWrapper(createUnimplementAdapter(HttpServletRequest.class), ex, postData, is);
ResponseWrapper resp = new ResponseWrapper(createUnimplementAdapter(HttpServletResponse.class), ex);
try {
servlet.service(req, resp);
resp.complete();
} catch (ServletException e) {
throw new IOException(e);
}
}
private static byte[] getBytes(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int r = in.read(buffer);
if (r == -1)
break;
out.write(buffer, 0, r);
}
return out.toByteArray();
}
#SuppressWarnings("unchecked")
private static <T> T createUnimplementAdapter(Class<T> httpServletApi) {
class UnimplementedHandler implements InvocationHandler {
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
throw new UnsupportedOperationException("Not implemented: " + method + ", args=" + Arrays.toString(args));
}
}
return (T) Proxy.newProxyInstance(UnimplementedHandler.class.getClassLoader(),
new Class<?>[] { httpServletApi },
new UnimplementedHandler());
}
}
You may also have a look at some NIO application framework such as:
Netty: http://jboss.org/netty
Apache Mina: http://mina.apache.org/ or its subproject AsyncWeb: http://mina.apache.org/asyncweb/
This code is better than ours, you only need to add 2 libs: javax.servelet.jar and org.mortbay.jetty.jar.
Class Jetty:
package jetty;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.mortbay.http.SocketListener;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHttpContext;
public class Jetty {
public static void main(String[] args) {
try {
Server server = new Server();
SocketListener listener = new SocketListener();
System.out.println("Max Thread :" + listener.getMaxThreads() + " Min Thread :" + listener.getMinThreads());
listener.setHost("localhost");
listener.setPort(8070);
listener.setMinThreads(5);
listener.setMaxThreads(250);
server.addListener(listener);
ServletHttpContext context = (ServletHttpContext) server.getContext("/");
context.addServlet("/MO", "jetty.HelloWorldServlet");
server.start();
server.join();
/*//We will create our server running at http://localhost:8070
Server server = new Server();
server.addListener(":8070");
//We will deploy our servlet to the server at the path '/'
//it will be available at http://localhost:8070
ServletHttpContext context = (ServletHttpContext) server.getContext("/");
context.addServlet("/MO", "jetty.HelloWorldServlet");
server.start();
*/
} catch (Exception ex) {
Logger.getLogger(Jetty.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Servlet class:
package jetty;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String appid = httpServletRequest.getParameter("appid");
String conta = httpServletRequest.getParameter("conta");
System.out.println("Appid : "+appid);
System.out.println("Conta : "+conta);
httpServletResponse.setContentType("text/plain");
PrintWriter out = httpServletResponse.getWriter();
out.println("Hello World!");
out.close();
}
}
I can strongly recommend looking into Simple, especially if you don't need Servlet capabilities but simply access to the request/reponse objects. If you need REST you can put Jersey on top of it, if you need to output HTML or similar there's Freemarker. I really love what you can do with this combination, and there is relatively little API to learn.
Starting in Java 18, you can create simple web servers with Java standard library:
class Main {
public static void main(String[] args) {
var port = 8000;
var rootDirectory = Path.of("C:/Users/Mahozad/Desktop/");
var outputLevel = OutputLevel.VERBOSE;
var server = SimpleFileServer.createFileServer(
new InetSocketAddress(port),
rootDirectory,
outputLevel
);
server.start();
}
}
This will, by default, show a directory listing of the root directory you specified. You can place an index.html file (and other assets like CSS and JS files) in that directory to show them instead.
Example (I put these in Desktop which was specified as my directory root above):
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Java 18 Simple Web Server</title>
<link rel="stylesheet" href="styles.css">
<style>h1 { color: blue; }</style>
<script src="scripts.js" defer>
let element = document.getElementsByTagName("h1")[0];
element.style.fontSize = "48px";
</script>
</head>
<body>
<h1>I'm <i>index.html</i> in the root directory.</h1>
</body>
</html>
Sidenote
For Java standard library HTTP client, see the post Java 11 new HTTP Client API.
An example of a very basic HTTP server on TCP sockets level:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class NaiveHttpServer {
public static void main(String[] args) throws IOException {
String hostname = InetAddress.getLocalHost().getHostName();
ServerSocket serverSocket = new ServerSocket(8089);
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String s = in.readLine();
System.out.println(s);
while ("\r\n".equals(in.readLine()));
if ("GET /hostname HTTP/1.1".equals(s)) {
out.println("HTTP/1.1 200 OK");
out.println("Connection: close");
out.println("Content-Type: text/plain");
out.println("Content-Length:" + hostname.length());
out.println();
out.println(hostname);
} else {
out.println("HTTP/1.1 404 Not Found");
out.println("Connection: close");
out.println();
}
out.flush();
}
}
}
The example serves the hostname of the computer.
checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..
Amazing!
Check out takes. Look at https://github.com/yegor256/takes for quick info
Try this https://github.com/devashish234073/Java-Socket-Http-Server/blob/master/README.md
This API has creates an HTTP server using sockets.
It gets a request from the browser as text
Parses it to retrieve URL info, method, attributes, etc.
Creates dynamic response using the URL mapping defined
Sends the response to the browser.
For example the here's how the constructor in the Response.java class converts a raw response into an http response:
public Response(String resp){
Date date = new Date();
String start = "HTTP/1.1 200 OK\r\n";
String header = "Date: "+date.toString()+"\r\n";
header+= "Content-Type: text/html\r\n";
header+= "Content-length: "+resp.length()+"\r\n";
header+="\r\n";
this.resp=start+header+resp;
}
How about Apache Commons HttpCore project?
From the web site:...
HttpCore Goals
Implementation of the most fundamental HTTP transport aspects
Balance between good performance and the clarity & expressiveness of
API
Small (predictable) memory footprint
Self contained library (no external dependencies beyond JRE)
You can write a pretty simple embedded Jetty Java server.
Embedded Jetty means that the server (Jetty) shipped together with the application as opposed of deploying the application on external Jetty server.
So if in non-embedded approach your webapp built into WAR file which deployed to some external server (Tomcat / Jetty / etc), in embedded Jetty, you write the webapp and instantiate the jetty server in the same code base.
An example for embedded Jetty Java server you can git clone and use: https://github.com/stas-slu/embedded-jetty-java-server-example
The old com.sun.net.httpserver is again a public and accepted API, since Java 11. You can get it as HttpServer class, available as part of jdk.httpserver module. See https://docs.oracle.com/en/java/javase/11/docs/api/jdk.httpserver/com/sun/net/httpserver/HttpServer.html
This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.
So, apart from its limitations, there is no reason to avoid its use anymore.
I use it to publish a control interface in server applications. Reading the User-agent header from a client request I even respond in text/plain to CLI tools like curl or in more elegant HTML way to any other browser.
Cool and easy.
Here is my simple webserver, used in JMeter for testing webhooks (that's why it will close and end itself after request is received).
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HttpServer {
private static int extractContentLength(StringBuilder sb) {
int length = 0;
String[] lines = sb.toString().split("\\n");
for (int i = 0; i < lines.length; i++) {
String s = lines[i];
if (s.toLowerCase().startsWith("Content-Length:".toLowerCase()) && i <= lines.length - 2) {
String slength = s.substring(s.indexOf(":") + 1, s.length()).trim();
length = Integer.parseInt(slength);
System.out.println("Length = " + length);
return length;
}
}
return 0;
}
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
System.out.println("starting HTTP Server on port " + port);
StringBuilder outputString = new StringBuilder(1000);
ServerSocket serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(3 * 60 * 1000); // 3 minutes timeout
while (true) {
outputString.setLength(0); // reset buff
Socket clientSocket = serverSocket.accept(); // blocking
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
try {
boolean isBodyRead = false;
int dataBuffer;
while ((dataBuffer = clientSocket.getInputStream().read()) != -1) {
if (dataBuffer == 13) { // CR
if (clientSocket.getInputStream().read() == 10) { // LF
outputString.append("\n");
}
} else {
outputString.append((char) dataBuffer);
}
// do we have Content length
int len = extractContentLength(outputString);
if (len > 0) {
int actualLength = len - 1; // we need to substract \r\n
for (int i = 0; i < actualLength; i++) {
int body = clientSocket.getInputStream().read();
outputString.append((char) body);
}
isBodyRead = true;
break;
}
} // end of reading while
if (isBodyRead) {
// response headers
out.println("HTTP/1.1 200 OK");
out.println("Connection: close");
out.println(); // must have empty line for HTTP
out.flush();
out.close(); // close clients connection
}
} catch (IOException ioEx) {
System.out.println(ioEx.getMessage());
}
System.out.println(outputString.toString());
break; // stop server - break while true
} // end of outer while true
serverSocket.close();
} // end of method
}
You can test it like this:
curl -X POST -H "Content-Type: application/json" -H "Connection: close" -d '{"name": "gustinmi", "email": "gustinmi at google dot com "}' -v http://localhost:8081/
I had some fun, I toyed around and pieced together this. I hope it helps you.
You are going to need Gradle installed or use Maven with a plugin.
build.gradle
plugins {
id 'application'
}
group 'foo.bar'
version '1.0'
repositories {
mavenCentral()
}
application{
mainClass.set("foo.FooServer")
}
dependencies {}
FooServer
The main entry point, your main class.
package foo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FooServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(7654);
serverSocket.setPerformancePreferences(0, 1, 2);
/* the higher the numbers, the better the concurrent performance, ha!
we found that a 3:7 ratio to be optimal
3 partitioned executors to 7 network executors */
ExecutorService executors = Executors.newFixedThreadPool(3);
executors.execute(new PartitionedExecutor(serverSocket));
}
public static class PartitionedExecutor implements Runnable {
ServerSocket serverSocket;
public PartitionedExecutor(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
#Override
public void run() {
ExecutorService executors = Executors.newFixedThreadPool(30);
executors.execute(new NetworkRequestExecutor(serverSocket, executors));
}
}
public static class NetworkRequestExecutor implements Runnable{
String IGNORE_CHROME = "/favicon.ico";
String BREAK = "\r\n";
String DOUBLEBREAK = "\r\n\r\n";
Integer REQUEST_METHOD = 0;
Integer REQUEST_PATH = 1;
Integer REQUEST_VERSION = 2;
String RENDERER;
Socket socketClient;
ExecutorService executors;
ServerSocket serverSocket;
public NetworkRequestExecutor(ServerSocket serverSocket, ExecutorService executors){
this.serverSocket = serverSocket;
this.executors = executors;
}
#Override
public void run() {
try {
socketClient = serverSocket.accept();
Thread.sleep(19);//do this for safari, its a hack but safari requires something like this.
InputStream requestInputStream = socketClient.getInputStream();
OutputStream clientOutput = socketClient.getOutputStream();
if (requestInputStream.available() == 0) {
requestInputStream.close();
clientOutput.flush();
clientOutput.close();
executors.execute(new NetworkRequestExecutor(serverSocket, executors));
return;
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int bytesRead;
while ((bytesRead = requestInputStream.read(byteBuffer.array())) != -1) {
byteArrayOutputStream.write(byteBuffer.array(), 0, bytesRead);
if (requestInputStream.available() == 0) break;
}
String completeRequestContent = byteArrayOutputStream.toString();
String[] requestBlocks = completeRequestContent.split(DOUBLEBREAK, 2);
String headerComponent = requestBlocks[0];
String[] methodPathComponentsLookup = headerComponent.split(BREAK);
String methodPathComponent = methodPathComponentsLookup[0];
String[] methodPathVersionComponents = methodPathComponent.split("\\s");
String requestVerb = methodPathVersionComponents[REQUEST_METHOD];
String requestPath = methodPathVersionComponents[REQUEST_PATH];
String requestVersion = methodPathVersionComponents[REQUEST_VERSION];
if (requestPath.equals(IGNORE_CHROME)) {
requestInputStream.close();
clientOutput.flush();
clientOutput.close();
executors.execute(new NetworkRequestExecutor(serverSocket, executors));
return;
}
ConcurrentMap<String, String> headers = new ConcurrentHashMap<>();
String[] headerComponents = headerComponent.split(BREAK);
for (String headerLine : headerComponents) {
String[] headerLineComponents = headerLine.split(":");
if (headerLineComponents.length == 2) {
String fieldKey = headerLineComponents[0].trim();
String content = headerLineComponents[1].trim();
headers.put(fieldKey.toLowerCase(), content);
}
}
clientOutput.write("HTTP/1.1 200 OK".getBytes());
clientOutput.write(BREAK.getBytes());
Integer bytesLength = "hi".length();
String contentLengthBytes = "Content-Length:" + bytesLength;
clientOutput.write(contentLengthBytes.getBytes());
clientOutput.write(BREAK.getBytes());
clientOutput.write("Server: foo server".getBytes());
clientOutput.write(BREAK.getBytes());
clientOutput.write("Content-Type: text/html".getBytes());
clientOutput.write(DOUBLEBREAK.getBytes());
clientOutput.write("hi".getBytes());
clientOutput.close();
socketClient.close();
executors.execute(new NetworkRequestExecutor(serverSocket, executors));
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ioException) {
ioException.printStackTrace();
}
}
}
}
Run it:
gradle run
Browse to:
http://localhost:7654/

Categories

Resources