forked from rizinorg/rizin-testbins
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Nim chatserver example (rizinorg#87)
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
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
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() |