Created
November 1, 2016 14:56
-
-
Save recoilme/a7222c5ef9229fbf7da53ddb6f8b340c to your computer and use it in GitHub Desktop.
This file contains 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
import asyncnet, asyncdispatch, strutils, tables | |
var clients {.threadvar.}: seq[AsyncSocket] | |
var die {.threadvar.}: bool | |
var dict {.threadvar.}:Table[string, string] | |
const bytes = 1000 | |
# The payload | |
const content = repeatStr(bytes, "x") | |
const response = "HTTP/1.1 200 OK\r\LContent-Length: " & $content.len & "\r\L\r\L" & content | |
proc closeClient(client: AsyncSocket) {.async.} = | |
client.close() | |
for i, c in clients: | |
if c == client: | |
clients.del(i) | |
break | |
proc processClient(client: AsyncSocket) {.async.} = | |
while true: | |
let line = await client.recvLine() | |
if line != "": | |
let | |
lines = splitLines(line) | |
commands = if lines.len>0: splitWhitespace(lines[0]) else: nil | |
command = if commands!=nil and commands.len>0:toLowerAscii(commands[0]) else: nil | |
case command: | |
of "set": | |
#set mykey 0 60 4\r\nda33\r\n | |
if commands.len<5: | |
await client.send("ERROR\r\L") | |
else: | |
let data = await client.recvLine() | |
dict.add(commands[1],data) | |
#echo repr(dict) | |
await client.send("STORED\r\L") | |
of "get": | |
if commands.len<2: | |
await client.send("ERROR\r\L") | |
else: | |
let val = dict.mget(commands[1]) | |
#VALUE <key> <flags> <bytes> [<cas unique>]\r\n | |
if val != nil: | |
await client.send("VALUE " & $commands[1] & " 0 " & $val.len & " \r\L") | |
await client.send(val & "\r\L") | |
await client.send("END\r\L") | |
of "quit": | |
asyncCheck closeClient(client) | |
break | |
of "suicide": | |
asyncCheck closeClient(client) | |
die = true | |
quit(1) | |
break | |
else: | |
await client.send("ERROR\r\L") | |
else: | |
#It seems sock received "", this it means connection has been closed. | |
asyncCheck closeClient(client) | |
break | |
proc serve() {.async.} = | |
clients = @[] | |
dict = initTable[string, string]() | |
#echo repr(dict) | |
var server = newAsyncSocket() | |
server.bindAddr(Port(11213)) | |
server.listen() | |
while not die: | |
let client = await server.accept() | |
clients.add client | |
asyncCheck processClient(client) | |
quit(1) | |
asyncCheck serve() | |
runForever() | |
#assert parse("hello world") == "hello" | |
#echo parse("\r\n") | |
#dict = initTable[string, string]() | |
#dict.add("1","2") | |
#echo repr(dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment