Skip to content

Commit

Permalink
Nim chatserver example (rizinorg#87)
Browse files Browse the repository at this point in the history
  • Loading branch information
wargio authored Sep 7, 2022
1 parent 7d0c31a commit aef7f7b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Binary file added nim/chatserver-dbg
Binary file not shown.
42 changes: 42 additions & 0 deletions nim/chatserver.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import asyncnet, asyncdispatch

type
Client = tuple
socket: AsyncSocket
name: string
connected: bool

var clients {.threadvar.}: seq[Client]

proc sendOthers(client: Client, line: string) {.async.} =
for c in clients:
if c != client and c.connected:
await c.socket.send(line & "\c\L")

proc processClient(socket: AsyncSocket) {.async.} =
await socket.send("Please enter your name: ")
var client: Client = (socket, await socket.recvLine(), true)

clients.add(client)
asyncCheck client.sendOthers("+++ " & client.name & " arrived +++")

while true:
let line = await client.socket.recvLine()
if line == "":
asyncCheck client.sendOthers("--- " & client.name & " leaves ---")
client.connected = false
return
asyncCheck client.sendOthers(client.name & "> " & line)

proc serve() {.async.} =
clients = @[]
var server = newAsyncSocket()
server.bindAddr(Port(4004))
server.listen()

while true:
let socket = await server.accept()
asyncCheck processClient(socket)

asyncCheck serve()
runForever()

0 comments on commit aef7f7b

Please sign in to comment.