|
| 1 | +# nim c -r --threads:on --tlsEmulation:off tests\chatclientthreads |
| 2 | + |
| 3 | +import netty, terminal |
| 4 | + |
| 5 | +var client = newReactor() |
| 6 | +var connection = client.connect("127.0.0.1", 2001) |
| 7 | + |
| 8 | +# get persons name |
| 9 | +echo "what is your name?" |
| 10 | +var name = readLine(stdin) |
| 11 | + |
| 12 | +# handle ctrl-c correclty on windows by stopping all threads |
| 13 | +proc handleCtrlC() {.noconv.} = |
| 14 | + setupForeignThreadGc() |
| 15 | + quit(1) |
| 16 | +setControlCHook(handleCtrlC) |
| 17 | + |
| 18 | +# create a thread that just reads a single chart |
| 19 | +var |
| 20 | + thread: Thread[tuple[a: int]] |
| 21 | + singleChar: char |
| 22 | +proc readSingleChar(interval: tuple[a: int]) {.thread.} = |
| 23 | + while true: |
| 24 | + singleChar = getch() |
| 25 | +createThread(thread, readSingleChar, (0, )) |
| 26 | + |
| 27 | +# main loop |
| 28 | +var line: string |
| 29 | +while true: |
| 30 | + client.tick() |
| 31 | + for packet in client.packets: |
| 32 | + # we got a packet, rase current line user is typing |
| 33 | + stdout.eraseLine() |
| 34 | + # write packet line |
| 35 | + echo packet.data |
| 36 | + # write back the line was typing |
| 37 | + writeStyled(line) |
| 38 | + |
| 39 | + if singleChar != char(0): |
| 40 | + if singleChar == char(8): |
| 41 | + # handle backspace |
| 42 | + line.setLen(line.len - 1) |
| 43 | + else: |
| 44 | + line.add(singleChar) |
| 45 | + # a char got added, erase current line |
| 46 | + stdout.eraseLine() |
| 47 | + # write the line again |
| 48 | + writeStyled(line & " ") |
| 49 | + # put cursor in right spot |
| 50 | + stdout.setCursorXPos(line.len) |
| 51 | + |
| 52 | + if singleChar == char(13): |
| 53 | + # handle sending |
| 54 | + connection.send(name & ":" & line) |
| 55 | + # clear line, reset eveything |
| 56 | + # server should echo the line back |
| 57 | + line = "" |
| 58 | + stdout.eraseLine() |
| 59 | + stdout.setCursorXPos(0) |
| 60 | + |
| 61 | + # reset character |
| 62 | + singleChar = char(0) |
0 commit comments