Skip to content

Instantly share code, notes, and snippets.

@chochos
Created March 25, 2016 19:32
Show Gist options
  • Save chochos/92600c2997b4f2ff9760 to your computer and use it in GitHub Desktop.
Save chochos/92600c2997b4f2ff9760 to your computer and use it in GitHub Desktop.
Braindead HTTP server
class BraindeadServer {
int port
private ServerSocket server
String response
void start() {
server = new ServerSocket(port)
byte[] buf = new byte[128]
new Thread({->
try {
while (true) {
Socket conn = server.accept()
conn.inputStream.read(buf)
conn.outputStream.write("HTTP/1.1 200 OK\nContent-Length: ".bytes)
conn.outputStream.write(Integer.toString(response.length()).bytes)
conn.outputStream.write("\n\n".bytes)
conn.outputStream.write(response.bytes)
conn.close()
}
} catch (SocketException ex) {
if (ex.message != 'Socket closed') {
ex.printStackTrace()
}
}
} as Runnable, 'braindead server').start()
}
void stop() {
server.close()
}
}
@chochos
Copy link
Author

chochos commented Mar 25, 2016

A very very simple http server which will not even properly read the request; it just reads a bit then writes the preset response and closes the connection.

I wrote this just to test an axis2 client that was having problems parsing a response.

@lucaswerkmeister
Copy link

That syntax is freaking me out. It looks so much like Java… but the semicolons are missing!

Also, you might want to use \r\n in the future. HTTP seems to allow \n in media (RFC 2616, 3.7.1 Canonicalization and Text Defaults, second paragraph), but if you use it in the headers, you’re probably just lucky if the user agent accepts it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment